Spring MVC 3: How to provide dynamic content for a page with an HTTP 404 error?

What I want:

I want to provide a model for the HTTP 404 error page. Instead of writing the static error page specified in web.xml, I want to use an exception controller that handles HTTP 404 errors.

What I've done:

Removed tag page with tags from web.xml:

<error-page> <error-code>404</error-code> <location>/httpError.jsp</location> </error-page> 

and the following exception handler methods are implemented inside my AbstractController class:

 @ExceptionHandler(NoSuchRequestHandlingMethodException.class) public ModelAndView handleNoSuchRequestException(NoSuchRequestHandlingMethodException ex) { ModelMap model = new ModelMap(); model.addAttribute("modelkey", "modelvalue"); return new ModelAndView("/http404Error", model); } @ExceptionHandler(NullPointerException.class) public ModelAndView handleAllExceptions(NullPointerException e) { ModelMap model = new ModelMap(); model.addAttribute("modelkey", "modelvalue"); return new ModelAndView("/exceptionError", model); } 

What is:

It works to look for exceptions, but not for the status of the HTTP 404 error code. It seems that HTTP 404 errors are handled by the default DispatcherServlet. Can this behavior be changed?

And how can I catch 404 errors in my exception handler?

+4
source share
2 answers

If you want to get dynamic content on page 404 or on any other error page, map the page to the controller in the context of spring. For example, declare a controller with the name "404.htm" and try requesting the /404.htm page to make sure that it works fine, then write the following in your web.xml:

 <error-page> <error-code>404</error-code> <location>/404.htm</location> </error-page> 
+2
source

Try this url http://blog.codeleak.pl/2013/04/how-to-custom-error-pages-in-tomcat.html

Explains how to create a controller to get an error, and set parameters to write them to .jsp.

0
source

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


All Articles