我们目前正在开发Play 2.5.x
我们希望能够完成不区分大小写的路由。比如说
GET / via / v1 / organizations http.organizationApi()
在我们希望获得的网址中
http://localhost:9000/abc/v1/organizations
http://localhost:9000/ABC/V1/OrganIZations
是否可以使用正则表达式来实现此功能?有人可以指出或提供一个例子吗?
答案 0 :(得分:3)
您可以定义请求处理程序以使URL不区分大小写。在这种情况下,以下处理程序只会将url转换为小写,因此在您的路由中,url应该以小写形式定义:
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"
现在,如果你有一个定义为“/ persons / create”的路由,那么无论什么案例组合都可行(例如:“/ PeRsOns / cREAtE”)
但有两点需要注意:
您只能在Scala操作中使用它。如果您的路由文件引用了Java控制器方法,您将得到一个奇怪的例外:
[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)
如果是这种情况,您可以找到更多信息here
如果您的网址有参数,那么这些参数也会被转换。例如,如果你有这样的路线
GET /persons/:name/greet ctrl.Persons.greet(name: String)
对“/ persons / JohnDoe / greet”的调用将转换为“/ persons / johndoe / greet”,并且您的greet
方法将接收“johndoe”而不是“JohnDoe”作为参数。请注意,这不适用于查询字符串参数。
根据您的使用情况,这可能会有问题。
答案 1 :(得分:0)
在播放2.8中,上述答案无效。播放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)
}
}