Is there a way to create a custom 404 page without web.xml?

Viewed 1706

So, basically, I am able to create a custom error page using web.xml:

 <error-page>
     <error-code>404</error-code>
     <location>/WEB-INF/pages/error/404.jsp</location>
 </error-page>

But so far, in my project, I do not use web.xml and tend to use only java code.

Is there a proper and easy way to do like in web.xml but without using it (create custom error page)? And if there is no such way then would it be a bad move to add web.xml only for handling custom error pages?

4 Answers

This is what @ControllerAdvice does in Spring MVC

@ControllerAdvice
public class GlobalExceptionHandler {
   @ExceptionHandler({NoHandlerFoundException.class})
   @ResponseStatus(value = HttpStatus.NOT_FOUND)
   public void handleNotFound(HttpSession session, HttpServletRequest req, HttpServletResponse httpServletResponse, Exception ex) {
   }
}

Also add this line to your WebApplicationInitializer

public class CCPMWebAppInitializer implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext servletContext) throws ServletException {

      // Create the 'root' Spring application context
      AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
      ....
       DispatcherServlet dispatcherServlet = new DispatcherServlet(rootContext);
       dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
      ...
  }

Well, as @MarkA.Fitzgerald mentioned in the comments:

The community seems to feel that there is no way to do this according to stackoverflow.com/a/13450154/1840078.

So, I guess, I can live with web.xml doing such simple stuff as creating custom error pages. I find it simple and clean instead of trying to "hardcode" it in java.

You can create a EmbeddedServletContainerCustomizer inside one of you configuration classes. Ex

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
    return container -> {
        ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/exceptions/not-found.jsp");

        container.addErrorPages(error404Page);
    };
}
Related