简体   繁体   中英

Getting an URL which led to error (404) from error-page controller 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 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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM