8

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 ?

1 Answer 1

15

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

Sign up to request clarification or add additional context in comments.

1 Comment

We are on a server supporting Servlet API 3.0.x but using 2.5 as of specification in the web.xml. With this setting the approaches above didn't yield anything usefull, but request.getAttribute("javax.servlet.error.request_uri"); did the trick

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.