2

I need to return a customized error page for HTTP 404, but the code does not work. I already read the stackflow 1,2, 3 and different online + articles but my case is quite different with those or at least I can not figure out the issue.

HTTP Status 404 -

type Status report

message

description The requested resource is not available.

For example, it is suggested to use an action name in web.xml to handle the exception, it might work but I think is not a good method of doing it.

I used following combinations:

1)

@Controller   //for class
@ResponseStatus(value = HttpStatus.NOT_FOUND) //for method

2)
 @Controller   //for class
 @ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
 @ExceptionHandler(ResourceNotFoundException.class) //for method

3)

@ControllerAdvice //for class
@ResponseStatus(value = HttpStatus.NOT_FOUND) //for method

3)

@ControllerAdvice //for class
@ResponseStatus(HttpStatus.NOT_FOUND) //for method

4)
 @ControllerAdvice   //for class
 @ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
 @ExceptionHandler(ResourceNotFoundException.class) //for method

Code

@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public String handleBadRequest(Exception exception) {
          return "error404";
    }
}
Community
  • 1
  • 1
Jack
  • 6,430
  • 27
  • 80
  • 151

3 Answers3

2

DispatcherServlet does not throw an exception by default, if it does not find the handler to process the request. So you need to explicitly activate it as below:

In web.xml:

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

If you are using annotation based configuration:

dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

In the controller advice class:

@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleExceptiond(NoHandlerFoundException ex) {
    return "errorPage";
}
Mithun
  • 7,747
  • 6
  • 52
  • 68
1

You can use the @ResponseStatus annotation at the class level. At least it works for me.

@Controller
@ResponseStatus(value=HttpStatus.NOT_FOUND)
public class GlobalExceptionHandler {
  ....  
}
Daniel Newtown
  • 2,873
  • 8
  • 30
  • 64
0

You can add the following in your web.xml to display an error page on 404. It will display 404.jsp page in views folder inside WEB-INF folder.

 <error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/404.jsp</location>
 </error-page>
M4ver1k
  • 1,505
  • 1
  • 15
  • 26
  • Thanks but this page cannot be customized, I need to send a request to back-end to send a customized error page based on each request. – Jack Apr 18 '15 at 00:27