What I want to do is that when user enters url which leads nowhere, I mean there is no resources by this url than special mapping should work.
For example, I have next controller:
@Controller
public class LoginController {
@RequestMapping(value = {"/", "/login"}, method = RequestMethod.GET)
public ModelAndView welcome() {
return new ModelAndView("mainPage");
}
}
This mapping works when when user enters {contextPath}/ or {contextPath}/login Now i want to map all other urls, I do like this:
@Controller
public class LoginController {
@RequestMapping(value = {"/", "/login"}, method = RequestMethod.GET)
public ModelAndView welcome() {
return new ModelAndView("mainPage");
}
@RequestMapping(value = {"/**"}, method = RequestMethod.GET)
public ModelAndView notFound() {
return new ModelAndView("customized404Page");
}
}
Now when user enters invalid path for example {contextPath}/sdfsdf customized404Page is shown to him
But last mapping is more general and and it works always and that is why first mapping doesn`t work.
Question: How to map all invalid urls? Or maybe there is some simplier way to to this in Spring?
The easiest way to have a customized 404 Page is to configure them in the web.xml
<error-page>
<error-code>404</error-code>
<location>/error404.jsp</location>
</error-page>
When a simple jsp
is not enough, because you need a full fledged Spring controller, then you can map the location to the controller`s mapping:
@Controller
public class HttpErrorController {
@RequestMapping(value="/error404")
public String error404() {
...
return "error404.jsp";
}
}
<error-page>
<error-code>404</error-code>
<location>/error404</location>
</error-page>