Custom Handling for 405 Error Using Spring Web MVC

In my application, I have several RequestMappings that only allow POST. If someone accidentally runs a GET request on this particular path, he gets a 405 error page loaded by the container (Tomcat). I can create and define a 405 error page in web.xml for customization.

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

What I tried:

  • a method with "method = GET" as an analog for each of the mappings mentioned. This works fine, but requires that I create an actual requestmapping and method for each path that only POST permits. I find this unnecessary duplication and mess.
  • global catch (requestmapping / *) method: this does not work, since Spring accepts the GET method as an invalid call to a path specified using only POST
  • ExceptionHandler-annotated method to handle HttpRequestMethodNotSupportedException class exceptions: this does not work. Spring seems to throw and throw this exception completely in its code.
  • specify your own 405 in web.xml. This is not ideal as I want to have custom processing, not a static error page.
+5
source share
2 answers

I would suggest using the Handler exception handler. You can use spring DefaultHandlerExceptionResolver . Override the handleHttpRequestMethodNotSupported() method and return the customized view . This will work in all your applications.

The effect is close to what you expected in option 3. The reason your annotated @ExceptionHandler method never falls into your exception is because these annotated ExceptionHandler methods are called after a successful spring controller handler mapping is found. However, this raises your exception.

+7
source
 Working Code: @ControllerAdvice public class GlobalExceptionController { @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public ModelAndView handleError405(HttpServletRequest request, Exception e) { ModelAndView mav = new ModelAndView("/405"); mav.addObject("exception", e); //mav.addObject("errorcode", "405"); return mav; } In Jsp page (405.jsp): <div class="http-error-container"> <h1>HTTP Status 405 - Request Method not Support</h1> <p class="message-text">The request method does not support. <a href="<c:url value="/"/>">home page</a>.</p> </div> 
+5
source

Source: https://habr.com/ru/post/1204184/


All Articles