Custom handling for 405 error with Spring Web MVC

后端 未结 2 1819
刺人心
刺人心 2020-12-30 08:28

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

相关标签:
2条回答
  • 2020-12-30 08:50

    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>
    
    0 讨论(0)
  • 2020-12-30 09:10

    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.

    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.

    0 讨论(0)
提交回复
热议问题