13

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.

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

What I've tried:

  • 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.

3 Answers 3

17

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.

1
  • 3
    This is perfect! One thing that others may need to watch out for is that if you decide to do this and override DefaultHandlerExceptionResolver, you should also override the getOrder() method specified in the interface Ordered. In that method, you should return any int lower than Integer.MAX_VALUE. The reason being the fact that the lowest ordered handler gets the first shot at the exception. Anyway, thanks!
    – Marceau
    Oct 7, 2014 at 15:32
12

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>
1
  • 1
    perfect, this answer taught me a new thing, i can now handle exceptions Nov 16, 2018 at 15:31
0
You can use spring DefaultHandlerExceptionResolver. 
Override handleHttpRequestMethodNotSupported() method and return your customized.
Status Code: 405




protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
            ApiError apiError = ApiError.builder()
                    .status(HttpStatus.METHOD_NOT_ALLOWED)
                    .message(ex.getMessage())
                    .build();
    
            return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
        }

Response Result:

{
    "status": "METHOD_NOT_ALLOWED",
    "message": "Request method 'POST' not supported",
    "errors": null
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.