简体   繁体   中英

Spring MVC: custom error page for 404s without web.xml file

I have a pretty big project with a lot of different controllers. I do have a main controller that has all of the mappings for the start of the program like (/login, /resetPassword, /logout, etc). I also do not have a web.xml file in the project. I need to add a custom error page for all unmapped requests. I have tried creating my own exception class and didn't work. Most of the solutions I find are to add error location to the web.xml. I would prefer not to have to create one but if anybody has any tips or can push me in the right direction that would help out so much. I've been stuck on this problem for a couple of days now. Thanks.

You should use 404 mapped to an error page in web.xml . Because it will handle even url requests that are not mapped to your DispatcherServlet . For example, imagine your Spring DispatcherServlet is mapped to any url ending in .htm , now some mistypes and tried to access something/somethingelse.do your application server will now present its own default error page to the user, which might not be pleasant.

The only time you should think about serving custom error pages from your MVC controllers, is when you have something specific to show the user. Specific as in, if an exception is encountered in this particular controller, I want to show a specific message, or redirect the user to a specific page. In these cases, you can use @ExceptionHandler methods in Spring controllers.

For more, look at this blog post, or refer the MVC documentation: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

See this answer: How to make a filter to detect if the user requested a page that is not found?

  1. Make a Filter
  2. Use HttpServletResponseWrapper and override the sendError() and setStatus()
  3. Pass the wrapped response through chain.doFilter(req, wrapper)
  4. If you get a sendError() in your wrapper, see if it's a 404.
  5. Take appropriate response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM