Scala Play框架路由不区分大小写

Scala Play框架路由不区分大小写,scala,playframework,playframework-2.0,Scala,Playframework,Playframework 2.0,我们目前正在开发Play2.5.x 我们希望实现不区分大小写的路由。比如说 GET/via/v1/organizations http.organizationApi() 在我们想要实现的URL中 使用正则表达式是实现这个bu的一种方法吗?有人能给我举个例子吗?您可以定义一个请求处理程序,使URL不区分大小写。在这种情况下,以下处理程序将仅将url转换为小写,因此在路由中,url应以小写形式定义: import javax.inject.Inject import play.api.htt

我们目前正在开发Play2.5.x

我们希望实现不区分大小写的路由。比如说

GET/via/v1/organizations http.organizationApi()

在我们想要实现的URL中


使用正则表达式是实现这个bu的一种方法吗?有人能给我举个例子吗?

您可以定义一个请求处理程序,使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) 
    
    如果这是你的情况,你可以找到更多信息

  • 如果您的url有参数,这些参数也将被转换。例如,如果您有这样一条路线

    GET /persons/:name/greet       ctrl.Persons.greet(name: String)
    
    对“/persons/JohnDoe/greet”的调用将转换为“/persons/JohnDoe/greet”,您的
    greet
    方法将接收“JohnDoe”而不是“JohnDoe”作为参数。请注意,这不适用于查询字符串参数。 根据您的用例,这可能会有问题


对于播放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)
}

}

@MipH早些时候看过这篇文章。我正在寻找一些正则表达式来处理这个问题。也许我能回答我到底需要什么的问题。谢谢我想你可能有兴趣读一下: