您的位置:首页 > 编程语言 > Java开发

play2.0文档-面向java开发者(2)

2012-04-06 13:17 549 查看

HTTProuting

Thebuilt-inHTTProuter(内置的HTTProuter)

TherouteristhecomponentthattranslateseachincomingHTTPrequesttoanactioncall(astatic,publicmethodinacontrollerclass).

router组件的功能是把收到的HTTPrequest转换成对action的调用(controller里的一个static,public方法).

AnHTTPrequestisseenasaneventbytheMVCframework.Thiseventcontainstwomajorpiecesofinformation:

一个HTTP请求被MVC框架看作是一个事件,这个事件包含两个主要的信息:

therequestpath(suchas/clients/1542,/photos/list),includingthequerystring.

theHTTPmethod(GET,POST,…).

请求路径(例如/clients/1542,/photos/list),包括查询字符串.

HTTP方法(GET,POST,...).

Routesaredefinedintheconf/routesfile,whichiscompiled.Thismeansthatyou’llseerouteerrorsdirectlyinyourbrowser:

Routes是在conf/routes文件中定义的,它会被编译,也就是说你可以直接在浏览器中看到route的错误。





Theroutesfilesyntax(routes文件语法)

conf/routesistheconfigurationfileusedbytherouter.Thisfilelistsalloftheroutesneededbytheapplication.EachrouteconsistsofanHTTPmethodandURIpatternassociatedwithacalltoanactionmethod.

conf/routes是router使用的配置文件。这个文件列出了应用程序所需要的所有routes。每个route由一个HTTP方法和一个与action调用相关联的URIpattern组成。

Let’sseewhataroutedefinitionlookslike:

来看一下route是怎样定义的:

GET/clients/:idcontrollers.Clients.show(id:Long)

Notethatintheactioncall,theparametertypecomesaftertheparametername,likeinScala.

注意在对action的调用中,参数类型在参数名称的后面,这有点像scala的定义方式。

EachroutestartswiththeHTTPmethod,followedbytheURIpattern.Thelastelementofarouteisthecalldefinition.

每个route的开头是HTTP方法,后面跟着URIpattern,最后面定义了会调用哪个action。

Youcanalsoaddcommentstotheroutefile,withthe#character:

你也可以在route文件中添加评论,用#来标识:

#Displayaclient.GET/clients/:idcontrollers.Clients.show(id:Long)

TheHTTPmethod

TheHTTPmethodcanbeanyofthevalidmethodssupportedbyHTTP(GET,POST,PUT,DELETE,HEAD).

HTTP方法可以是HTTP支持的任何一种有效的方法(GET,POST,PUT,DELETE,HEAD).

TheURIpattern

TheURIpatterndefinestheroute’srequestpath.Somepartsoftherequestpathcanbedynamic.

URIpattern表示route的请求路径.这个请求路径的某些部分可以是动态的。

Staticpath(静态路径)

Forexample,toexactlymatchGET/clients/allincomingrequests,youcandefinethisroute:

例如,为了提取与GET/clients/all相匹配的请求,你可以这样定义:

GET/clientscontrollers.Clients.list()

Dynamicparts(动态部分)

Ifyouwanttodefinearoutethat,say,retrievesaclientbyid,youneedtoaddadynamicpart:

如果你想定义一个通过id来获取一个client的路由,你就需要添加一个动态的部分:

GET/clients/:idcontrollers.Clients.show(id:Long)

NotethataURIpatternmayhavemorethanonedynamicpart.

注意一个URIpattern可以有不止一个动态部分.

Thedefaultmatchingstrategyforadynamicpartisdefinedbytheregularexpression[^/]+,meaningthatanydynamicpartdefinedas:idwillmatchexactlyoneURIpathsegment.

对于动态部分的默认匹配策略是由正则表达式[^/]+定义的,这意味着任何被定义成:id的动态部分将会被准确的匹配到一个URI的路径部分。

Dynamicpartsspanningseveral/(跨越多个/的动态部分)

IfyouwantadynamicparttocapturemorethanoneURIpathsegment,separatedbyforwardslashes,youcandefineadynamicpartusingthe*idsyntax,whichusesthe.*regularexpression:

如果你想用一个动态部分来捕获多个独立的URI路径段,你可以使用正则表达式的*id语法来定义一个动态部分:

GET/files/*namecontrollers.Application.download(name)
Here,forarequestlikeGET/files/images/logo.png,thenamedynamicpartwillcapturetheimages/logo.pngvalue.

对于一个像GET/files/images/logo.png的请求来说,name的动态部分将会捕获images/logo.png这个值

Dynamicpartswithcustomregularexpressions

自定义的正则表达式动态部分

Youcanalsodefineyourownregularexpressionforadynamicpart,usingthe$id<regex>syntax:

你也可以使用$id<regex>语法来为动态部分定义自己的正则表达式:

GET/clients/$id<[0-9]+>controllers.Clients.show(id:Long)

Calltoactiongeneratormethod

调用action的产生器方法

Thelastpartofaroutedefinitionisthecall.Thispartmustdefineavalidcalltoanactionmethod.

route定义的最后一部分是调用。这部分必须定义一个有效的对action方法的调用。

Ifthemethoddoesnotdefineanyparameters,justgivethefully-qualifiedmethodname:

如果方法没有定义任何参数,就只需给出一个合法的方法名:

GET/controllers.Application.homePage()
Iftheactionmethoddefinesparameters,thecorrespondingparametervalueswillbesearchedforintherequestURI,eitherextractedfromtheURIpathitself,orfromthequerystring.

如果action方法定义了参数,相对应的参数值需要从请求的URI中寻找,或者从URI路径本身提取,或者从查询字符串中提取。

#Extractthepageparameterfromthepath.#i.e.http://myserver.com/indexGET/:pagecontrollers.Application.show(page)
Or:

#Extractthepageparameterfromthequerystring.#i.e.http://myserver.com/?page=indexGET/controllers.Application.show(page)
Hereisthecorrespondingshowmethoddefinitioninthecontrollers.Applicationcontroller:

这是一个在controllers.Application中定义的与show方法对应的controller

publicstaticResultshow(Stringpage){Stringcontent=Page.getContentOf(page);response().setContentType("text/html");returnok(content);}

Parametertypes(参数类型)

Forparametersoftype
String,theparametertypeisoptional.IfyouwantPlaytotransformtheincomingparameterintoaspecificScalatype,youcanaddanexplicittype:

对于String类型,参数类型是可选的。如果你想把收到的参数转换成指定的scala类型,你可以显示的添加上。

GET/client/:idcontrollers.Clients.show(id:Long)
Thenusethesametypeforthecorrespondingactionmethodparameterinthecontroller:

并且在controller中相应的action方法参数也需要使用相同的类型。

publicstaticResultshow(Longid){

Clientclient=Client.findById(id);

returnok(views.html.Client.show(client));

}

Note:Theparametertypesarespecifiedusingasuffixsyntax.AlsoThegenerictypesarespecifiedusingthe[]symbolsinsteadof<>,asinJava.Forexample,List[String]isthesametypeastheJavaList<String>.

注意:参数类型是使用后缀语法定义的,泛型是使用[]符号定义,而不是像java一样使用<>定义。例如,

List[String]和Java
List<String>是同一种类型

Parameterswithfixedvalues(带有固定值的参数)

Sometimesyou’llwanttouseafixedvalueforaparameter:

有时候你可能想使用固定值作为参数:

#Extractthepageparameterfromthepath,orfixthevaluefor/GET/controllers.Application.show(page="home")GET/:pagecontrollers.Application.show(page)

Parameterswithdefaultvalues(带有默认值的参数)

Youcanalsoprovideadefaultvaluethatwillbeusedifnovalueisfoundintheincomingrequest:

你也可以提供一个默认值,如果收到的请求中没找到参数的值就会使用这个默认值。

#Paginationlinks,like/clients?page=3GET/clientscontrollers.Clients.list(page:Integer?=1)

Routingpriority(路由优先级)

Manyroutescanmatchthesamerequest.Ifthereisaconflict,thefirstroute(indeclarationorder)isused.

许多routes可以匹配相同的请求,如果有冲突的话就会使用声明中的第一个route。

Reverserouting(反转路由)

TheroutercanbeusedtogenerateaURLfromwithinaJavacall.ThismakesitpossibletocentralizeallyourURIpatternsinasingleconfigurationfile,soyoucanbemoreconfidentwhenrefactoringyourapplication.

router可以根据一个java调用来产生一个URL。这使得在一个配置文件里集中配置所有你的URIpattern变得可能,这样,当你做重构是就会更加自信。

Foreachcontrollerusedintheroutesfile,therouterwillgeneratea‘reversecontroller’intheroutespackage,havingthesameactionmethods,withthesamesignature,butreturningaplay.mvc.Callinsteadofaplay.mvc.Result.

对于routes文件中的每一个controller,router都会在routes包里生成一个'反转controller',它有相同的action方法,相同的特征,但是返回的却是一个play.mvc.Call而不是play.mvc.Result。

Theplay.mvc.CalldefinesanHTTPcall,andprovidesboththeHTTPmethodandtheURI.

play.mvc.Call定义了一个HTTP调用,而且还提供了HTTP方法和URI.

Forexample,ifyoucreateacontrollerlike:

举个例子,如果你创建一个像这样的controller:

packagecontrollers;

importplay.*;

importplay.mvc.*;

publicclassApplicationextendsController{

publicstaticResulthello(Stringname){

returnok("Hello"+name+"!");

}

}

Andifyoumapitintheconf/routesfile:

然后你在conf/routes文件中配置映射关系:

#HelloactionGET/hello/:namecontrollers.Application.hello(name)
YoucanthenreversetheURLtothehelloactionmethod,byusingthecontrollers.routes.Applicationreversecontroller:

你就可以通过使用controllers.routes.Application反转controller把URL反转到helloaction方法

//Redirectto/hello/Bob

publicstaticResultindex(){

returnredirect(controllers.routes.Application.hello("Bob"));

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: