Play2:如果路由存在,是否可以用“405 Method not allowed”而不是“404 Not Found”来响应,但不是当前方法
Play2: Is it possible to respond with 405 Method not allowed" instead of "404 Not Found" if a route exists, but not for the current method
当我将类似这样的内容放入我的路由文件中时:
GET /foo com.example.controllers.FooController.foo
然后向这个不是 GET
的资源发出请求,例如POST /foo
,默认路由器以 404 和 "Action not found" 响应。是否有可能让它检测到不同方法存在资源并输出状态代码 405(方法不允许)?
您需要覆盖 GlobalSettings
中的 onHandlerNotFound
方法 class:
Called when no action was found to serve a request. The default behavior is to render the framework's default 404 page. This is achieved by returning null, so that the Scala engine handles onHandlerNotFound. By overriding this method one can provide an alternative 404 page.
更多详情here。
只需在您的 APP 文件夹中添加 Class Global 并像这样覆盖方法 onHandlerNotFound:
import play.*;
import play.mvc.*;
import play.mvc.Http.*;
import play.libs.F.*;
import static play.mvc.Results.*;
public class Global extends GlobalSettings {
public Promise<Result> onHandlerNotFound(RequestHeader request) {
return Promise.<Result>pure(
status(405, "Method Not Allowed")
);
}
}
Play framewrok 没有不允许的结果所以你必须使用 Status https://www.playframework.com/documentation/2.3.x/api/java/index.html
我认为你应该写一点 DSL 或自定义路由,看看方法和路径你有一个与动作组合相关的动作在博客中有很好的解释 post:
scala中的代码
override def onRouteRequest(req: RequestHeader): Option[Handler] = {
(req.method, req.path) match {
case ("GET", "/") => Some(controllers.Application.index)
case ("POST", "/submit") => Some(controllers.Application.submit)
case _ => None
}
}
here 是博客条目。
当我将类似这样的内容放入我的路由文件中时:
GET /foo com.example.controllers.FooController.foo
然后向这个不是 GET
的资源发出请求,例如POST /foo
,默认路由器以 404 和 "Action not found" 响应。是否有可能让它检测到不同方法存在资源并输出状态代码 405(方法不允许)?
您需要覆盖 GlobalSettings
中的 onHandlerNotFound
方法 class:
Called when no action was found to serve a request. The default behavior is to render the framework's default 404 page. This is achieved by returning null, so that the Scala engine handles onHandlerNotFound. By overriding this method one can provide an alternative 404 page.
更多详情here。
只需在您的 APP 文件夹中添加 Class Global 并像这样覆盖方法 onHandlerNotFound:
import play.*;
import play.mvc.*;
import play.mvc.Http.*;
import play.libs.F.*;
import static play.mvc.Results.*;
public class Global extends GlobalSettings {
public Promise<Result> onHandlerNotFound(RequestHeader request) {
return Promise.<Result>pure(
status(405, "Method Not Allowed")
);
}
}
Play framewrok 没有不允许的结果所以你必须使用 Status https://www.playframework.com/documentation/2.3.x/api/java/index.html
我认为你应该写一点 DSL 或自定义路由,看看方法和路径你有一个与动作组合相关的动作在博客中有很好的解释 post:
scala中的代码
override def onRouteRequest(req: RequestHeader): Option[Handler] = {
(req.method, req.path) match {
case ("GET", "/") => Some(controllers.Application.index)
case ("POST", "/submit") => Some(controllers.Application.submit)
case _ => None
}
}
here 是博客条目。