How to handle 404 page exception in Spring MVC with java configuration and without Web.xml

I want to handle a 404 page exception not found in my Spring MVC web application, I am using SPRING 4.2.5.RELEASE , I read a few questions regarding this topic, but similar questions use a different java w760 configuration.

I have a global exception handler controller class that has all my exceptions, this class works fine, but I cannot handle an exception of 404 pages.

This is the approach that I take after the tutorial

1) I created a class called ResourceNotFoundException that extends from RuntimeException , and I put this annotation on top of the definition of the @ResponseStatus(HttpStatus.NOT_FOUND) class @ResponseStatus(HttpStatus.NOT_FOUND)

like this:

 @ResponseStatus(HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { } 

2) I created this method in an exception class class

 @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public String handleResourceNotFoundException() { return "notFoundJSPPage"; } 

But still, when I put a URL that does not exist, I get this error "No mapping for HTTP request with URI"

The questions I read say that I need to enable true for the Dispatcher parameter, but since my configuration is different from other questions and I don't have Web.xml , I could not apply this.

Here he is my Config.java

 @EnableWebMvc @Configuration @ComponentScan({"config", "controllers"}) public class ConfigMVC extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); } @Bean public UrlBasedViewResolver setupViewResolver() { UrlBasedViewResolver resolver = new UrlBasedViewResolver(); resolver.setPrefix("/WEB-INF/jsp/"); resolver.setSuffix(".jsp"); resolver.setViewClass(JstlView.class); return resolver; } } 

Here is my WebInitializer

 public class WebInicializar implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(ConfigMVC.class); ctx.setServletContext(servletContext); Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.addMapping("/"); servlet.setLoadOnStartup(1); } } 

Here is my global exception handler controller

 @ControllerAdvice public class GlobalExceptionHandlerController { @ExceptionHandler(value = NullPointerException.class) public String handleNullPointerException(Exception e) { System.out.println("A null pointer exception ocurred " + e); return "nullpointerExceptionPage"; } @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(value = Exception.class) public String handleAllException(Exception e) { System.out.println("A unknow Exception Ocurred: " + e); return "unknowExceptionPage"; } @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public String handleResourceNotFoundException() { return "notFoundJSPPage"; } } 

And the class I created that extends the runtime exception

 @ResponseStatus(HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException{ } 
+5
source share
4 answers

I solved the problem by putting this line in my onStartup method in WebApplicationInitializer.class

this is the line I'm adding servlet.setInitParameter("throwExceptionIfNoHandlerFound", "true");

this is what the full method looks like with the new line I added

 @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(ConfigMVC.class); ctx.setServletContext(servletContext); Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.addMapping("/"); servlet.setLoadOnStartup(1); servlet.setInitParameter("throwExceptionIfNoHandlerFound", "true"); } 

Then I created this controller method in my GlobalExceptionHandlerController.class

 @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public String handle(NoHandlerFoundException ex) { return "my404Page"; } 

and that solved my problem. I removed the controller method handleResourceNotFoundException in my GlobalExceptionHandlerController.class , as it was not needed, and I also deleted the ResourceNotFoundException.class exception class that I created

+6
source

You can also extend AbstractAnnotationConfigDispatcherServletInitializer and override this method:

 @Override protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) { final DispatcherServlet dispatcherServlet = (DispatcherServlet) super.createDispatcherServlet(servletAppContext); dispatcherServlet.setThrowExceptionIfNoHandlerFound(true); return dispatcherServlet; } 

OR this one:

 @Override public void customizeRegistration(ServletRegistration.Dynamic registration) { registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); } 

And finally, in your ControlerAdvice use this:

 @ExceptionHandler(NoHandlerFoundException.class) public String error404(Exception ex) { return new ModelAndView("404"); } 
+1
source

I found that the answer of zygimantus for some reason does not work, so if you also have the same problem, instead of declaring "@ExceptionHandler", instead add one of them to the "@Configuration" class. I put mine in my WebMvcConfigurerAdapter

 @Bean public HandlerExceptionResolver handlerExceptionResolver(){ HandlerExceptionResolver myResolver = new HandlerExceptionResolver(){ @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) { //return your 404 page ModelAndView mav = new ModelAndView("404page"); mav.addObject("error", exception); return mav; } }; return myResolver; } 

But make sure that you also follow the rest of zygimantus, i.e.

 dispatcherServlet.setThrowExceptionIfNoHandlerFound(true); 
+1
source

Add the following code to any controller and create a 404 page

 @GetMapping("/*") public String handle() { return "404"; } 
0
source

Source: https://habr.com/ru/post/1245047/


All Articles