1

I would like to display custom 404 error page if a user enters a request path that isn't handled by any controller.

Suppose that I have only one controller and it handles the following request paths: path1, path2 and path3. How can I display a custom 404 error page if a user enters path4? Currently, Tomcat displays its own 404 error page. I would like to use annotations and not implement this task by configuring any xml files.

My current approach doesn't achieve this requirement.It might be possible to configure any filters, but I am not aware of such approach. Thus, I will appreciate any ideas about it.

Here is my code:

public class WebAppContextInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
        annotationConfigWebApplicationContext.register(WebContextConfiguration.class);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(annotationConfigWebApplicationContext);
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("SpringDispatcher",dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
        servletContext.setInitParameter("spring.profiles.active","demo");
    }
}

@ControllerAdvice
class GlobalControllerExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    public String handleConflict() {
        return "404_error_page";
    }
}
Ravish
  • 2,383
  • 4
  • 37
  • 55
mr.M
  • 851
  • 6
  • 23
  • 41

0 Answers0