Custom handling for 405 error with Spring Web MVC

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.


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>