play framework2: remove trailing slash from urls

前端 未结 5 884
暗喜
暗喜 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:46

    This is based on opensas's answer, just simplified a bit to reuse Play's built-in copy method on RequestHeader so that all the things in the original RequestHeader are kept, like id, tags, version, secure, etc.

    import play.api.GlobalSettings
    import play.api.mvc.{Handler, RequestHeader}
    
    trait TrailingSlashNormaliser extends GlobalSettings {
    
      def removeTrailingSlash(origReq: RequestHeader): RequestHeader = {
        if (origReq.path.endsWith("/")) {
          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
        }
      }
    
      override def onRouteRequest(request: RequestHeader): Option[Handler] = 
        super.onRouteRequest(removeTrailingSlash(request))
    
    }
    
    /**
     * Global object that removes trailing slashes from requests.
     */
    object Global extends TrailingSlashNormaliser
    

提交回复
热议问题