play framework2: remove trailing slash from urls

前端 未结 5 886
暗喜
暗喜 2020-12-13 13:59

In play framework 1, you could use in the routes file something like this (check documentation at http://www.playframework.org/documentation/1.2.5/routes#syntax)

<         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 14:36

    Updated the example by @opensas and @lloydmeta for play 2.5

    /**
      * HttpRequestHandler that removes trailing slashes from requests.
      */
    class TrailingSlashNormaliserHttpRequestHandler(router: Router, errorHandler: HttpErrorHandler, configuration: HttpConfiguration, filters: HttpFilters) extends HttpRequestHandler {
    
      private val default = new DefaultHttpRequestHandler(router, errorHandler, configuration, filters)
    
      override def handlerForRequest(request: RequestHeader): (RequestHeader, Handler) = {
        default.handlerForRequest(removeTrailingSlash(request))
      }
    
      private def removeTrailingSlash(origReq: RequestHeader): RequestHeader = {
        if (origReq.path.endsWith("/") && origReq.path != "/") {
          val path = origReq.path.stripSuffix("/")
          if (origReq.rawQueryString.isEmpty) {
            origReq.copy(path = path, uri = path)
          }else {
            origReq.copy(path = path, uri = path + s"?${origReq.rawQueryString}")
          }
        } else {
          origReq
        }
      }
    }
    

    see https://www.playframework.com/documentation/2.5.x/ScalaHttpRequestHandlers for instructions on how to apply the handler

提交回复
热议问题