Play框架路由不区分大小写

3

https://dev59.com/bXzaa4cB1Zd3GeqPWOty - MipH
@MipH之前已经看到了这篇帖子。我正在寻找一些正则表达式来处理这个问题。也许我可以更新问题,明确我需要什么。谢谢。 - Prakash
我认为你可能会有兴趣阅读这篇文章:https://jazzy.id.au/2013/05/08/advanced_routing_in_play_framework.html - Alexander Arendar
2个回答

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”)。
不过有两个注意事项:
  • 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.


0

使用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)
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接