我们目前正在使用Play 2.5.x。
我们希望能够实现不区分大小写的路由。例如:
GET /via/v1/organizations http.organizationApi()
在URL中,我们希望实现:
http://localhost:9000/abc/v1/organizations
http://localhost:9000/ABC/V1/OrganIZations
有没有一种方法可以使用正则表达式来实现这个目标?能否提供一个例子或者指点一下?
我们目前正在使用Play 2.5.x。
我们希望能够实现不区分大小写的路由。例如:
GET /via/v1/organizations http.organizationApi()
在URL中,我们希望实现:
http://localhost:9000/abc/v1/organizations
http://localhost:9000/ABC/V1/OrganIZations
有没有一种方法可以使用正则表达式来实现这个目标?能否提供一个例子或者指点一下?
import javax.inject.Inject
import play.api.http._
import play.api.mvc.RequestHeader
import play.api.routing.Router
class MyReqHandler @Inject() (router: Router, errorHandler: HttpErrorHandler,
configuration: HttpConfiguration, filters: HttpFilters
) extends DefaultHttpRequestHandler(router, errorHandler, configuration, filters) {
override def routeRequest(request: RequestHeader) = {
val newpath = request.path.toLowerCase
val copyReq = request.copy(path = newpath)
router.handlerFor(copyReq)
}
}
在application.conf
中引用它:
# This supposes MyReqHandler.scala is in your project app folder
# If it is in another place reference it using the correct package name
# ex: app/handlers/MyReqHandler.scala --> "handlers.MyReqHandler"
play.http.requestHandler = "MyReqHandler"
You can only use this with Scala actions. If your routes file references a Java controller method, you will get an odd exception:
[error] p.c.s.n.PlayRequestHandler - Exception caught in Netty
scala.MatchError: Right((play.core.routing.HandlerInvokerFactory$JavaActionInvokerFactory$$anon$14$$anon$3@22d56da6,play.api.DefaultApplication@67d7f798)) (of class scala.util.Right)
If this is your case you can find more info here
If your url have parameters, those will also be transformed. For example, if you have a route like this
GET /persons/:name/greet ctrl.Persons.greet(name: String)
a call to "/persons/JohnDoe/greet" will be transformed to "/persons/johndoe/greet", and your greet
method will receive "johndoe" instead of "JohnDoe" as parameter. Note that this does not apply to query string parameters.
Depending in your use case, this can be problematic.
使用Play 2.8,上面的答案不起作用。Play API已更改,所以我在这里粘贴了我的代码。
class CaseInsensitive @Inject()(router: Router, errorHandler: HttpErrorHandler, configuration: HttpConfiguration, filters: EssentialFilter*)
extends DefaultHttpRequestHandler(new DefaultWebCommands, None, router, errorHandler, configuration, filters){
override def routeRequest(request: RequestHeader): Option[Handler] = {
val target = request.target;
val newPath = target.path.toLowerCase
val newTarget = request.target.withPath(newPath)
val newRequest = request.withTarget(newTarget);
router.handlerFor(newRequest)
}
}