使用Spring Web MVC自定义处理405错误 [英] Custom handling for 405 error with Spring Web MVC

查看:186
本文介绍了使用Spring Web MVC自定义处理405错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一些只允许POST的RequestMappings。如果有人碰巧在该特定路径上发出GET请求,则会收到容器(Tomcat)提供的405错误页面。我可以在web.xml中创建并定义405错误页面以进行自定义。

In my application, I have a few RequestMappings that only allow POST. If someone happens to fire a GET request at that particular path, they get a 405 error page fed by the container (Tomcat). I can create and define a 405 error page in web.xml for customization.

我想要的是:任何导致405错误的请求都应该在特定的处理中处理控制器方法。

What I want: any request that would result in a 405 error should be handled in a specific controller method.

我尝试了什么:


  • 方法 method = GET作为所提到的每个映射的对应物。这工作正常,但要求我为每个只允许POST的路径创建一个实际的请求映射和方法。我发现这种不必要的重复和混乱。

  • 一个全局'catch'方法(requestmapping / *):这不起作用,因为Spring将GET方法作为对路径的错误调用仅使用POST指定

  • 用于处理类HttpRequestMethodNotSupportedException异常的ExceptionHandler-annotated方法:这不起作用。似乎Spring在其框架代码中完全抛出并捕获此异常。

  • 在web.xml中指定我自己的405。这并不完美,因为我想要自定义处理而不是静态错误页面。

  • a method with "method = GET" as a counterpart for each of the mappings mentioned. This works fine, but requires me to create an actual requestmapping and method for every path that only allows POST. I find this unnecessary duplication and clutter.
  • a global 'catch' method (requestmapping /*): this does not work, as Spring takes the GET method to be a wrong call to the path specified with POST only
  • an ExceptionHandler-annotated method to handle exceptions of class HttpRequestMethodNotSupportedException: this does not work. It seems that Spring throws and catches this exception entirely in its framework code.
  • specify my own 405 in web.xml. This is not perfect, as I want to have customized handling rather than a static error page.

推荐答案

我建议使用Handler Exception Resolver。你可以使用spring的 DefaultHandlerExceptionResolver 。覆盖 handleHttpRequestMethodNotSupported()方法并返回自定义的视图。这将适用于您的所有应用程序。

I would suggest using a Handler Exception Resolver. You can use spring's DefaultHandlerExceptionResolver. Override handleHttpRequestMethodNotSupported() method and return your customized view. This will work across all of your application.

效果接近您在选项3中的预期效果。 @ExceptionHandler 带注释的方法的原因从未捕获异常是因为在找到成功的Spring控制器处理程序映射后会调用这些ExceptionHandler带注释的方法。但是,在此之前会引发您的异常。

The effect is close to what you were expecting in your option 3. The reason your @ExceptionHandler annotated method never catches your exception is because these ExceptionHandler annotated methods are invoked after a successful Spring controller handler mapping is found. However, your exception is raised before that.

这篇关于使用Spring Web MVC自定义处理405错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆