Extending on BwithLove comment, you can define 404 error page using exception and controller method which is @ExceptionHandler:
- Enable throwing NoHandlerFoundException in DispatcherServlet.
- Use @ControllerAdvice and @ExceptionHandler in controller.
WebAppInitializer class:
public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
DispatcherServlet dispatcherServlet = new DispatcherServlet(getContext());
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
ServletRegistration.Dynamic registration = container.addServlet("dispatcher", dispatcherServlet);
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.my.config");
context.scan("com.my.controllers");
return context;
}
}
Controller class:
@Controller
@ControllerAdvice
public class MainController {
@RequestMapping(value = "/")
public String whenStart() {
return "index";
}
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public String requestHandlingNoHandlerFound(HttpServletRequest req, NoHandlerFoundException ex) {
return "error404";
}
}
"error404" is a JSP file.