Getting the URL that led to the error (404) from the page controller with the error in spring MVC

Say I have a Spring MVC application with the following web.xml entry:

<error-page> <error-code>404</error-code> <location>/error/404</location> </error-page> 

and the following error page controller:

 @RequestMapping({"","/"}) @Controller public class RootController { @RequestMapping("error/{errorId}") public String errorPage(@PathVariable Integer errorId, Model model) { model.addAttribute("errorId",errorId); return "root/error.tile"; } } 

Now the user requested a non-existent URL / user / show / iamnotauser, which called the error page controller. How to get this non-existent url '/ user / show / iamnotauser' from the errorPage () method of RootController to put it in the model and display it on the error page?

+7
source share
1 answer

The trick is a javax.servlet.forward.request_uri request attribute, it contains the original requested uri.

 @RequestMapping("error/{errorId}") public ModelAndView resourceNotFound(@PathVariable Integer errorId, HttpServletRequest request) { //request.getAttribute("javax.servlet.forward.request_uri"); String origialUri = (String) request.getAttribute( RequestDispatcher.FORWARD_REQUEST_URI); return new ModelAndView("root/error.jspx", "originalUri", origialUri); } 

If you are still using Servlet API 2.5, the RequestDispatcher.FORWARD_REQUEST_URI constant RequestDispatcher.FORWARD_REQUEST_URI not exist, but you can use request.getAttribute("javax.servlet.forward.request_uri") . or upgrade to javax.servlet:javax.servlet-api:3.0.1

+14
source

All Articles