Reputation: 1591
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 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 user requested non-existent URL /user/show/iamnotauser which triggered error page controller. How do i get this non-existent '/user/show/iamnotauser' URL from errorPage() method of RootController to put it into model and display on error page ?
Upvotes: 8
Views: 3858
Reputation: 120871
The trick is request attribute javax.servlet.forward.request_uri
, 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 still use Servlet API 2.5, then the constant RequestDispatcher.FORWARD_REQUEST_URI
does not exist, but you can use request.getAttribute("javax.servlet.forward.request_uri")
. or upgrad to javax.servlet:javax.servlet-api:3.0.1
Upvotes: 15