简体   繁体   English

从Spring MVC中的错误页面控制器获取导致错误(404)的URL

[英]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: 说,我有一个带有以下web.xml条目的Spring MVC应用程序:

<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. 现在用户请求不存在的URL / user / show / iamnotauser,它触发了错误页面控制器。 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 ? 如何从RootController的errorPage()方法获取这个不存在的'/ user / show / iamnotauser'URL以将其放入模型并显示在错误页面上?

The trick is request attribute javax.servlet.forward.request_uri , it contains the original requested uri. 技巧是请求属性javax.servlet.forward.request_uri ,它包含原始请求的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") . 如果仍然使用Servlet API 2.5,则常量RequestDispatcher.FORWARD_REQUEST_URI不存在,但您可以使用request.getAttribute("javax.servlet.forward.request_uri") or upgrad to javax.servlet:javax.servlet-api:3.0.1 或者升级到javax.servlet:javax.servlet-api:3.0.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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