Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 988
jergamb Avatar asked Nov 10 '22 07:11

jergamb


1 Answers

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

like image 55
Akshay Avatar answered Nov 14 '22 22:11

Akshay