Spring MVC 3: How to provide dynamic content to error page for HTTP 404 errors?

淺唱寂寞╮ 提交于 2019-12-22 08:31:22

问题


What I want:

I want to provide a model to the HTTP 404 error page. Instead of writing a static error Page, which is specified within web.xml, I want to use an exception controller, which handles HTTP 404 errors.

What I did:

Removed error page tag from web.xml:

<error-page>
    <error-code>404</error-code>
    <location>/httpError.jsp</location>
</error-page>

and implemented the following exception handler methods inside my AbstractController class:

@ExceptionHandler(NoSuchRequestHandlingMethodException.class)
public ModelAndView handleNoSuchRequestException(NoSuchRequestHandlingMethodException ex) {
    ModelMap model = new ModelMap();
        model.addAttribute("modelkey", "modelvalue");
        return new ModelAndView("/http404Error", model);
}

@ExceptionHandler(NullPointerException.class)
public ModelAndView handleAllExceptions(NullPointerException e) {
        ModelMap model = new ModelMap();
        model.addAttribute("modelkey", "modelvalue");
        return new ModelAndView("/exceptionError", model);
}

What is does:

It works find for exceptions, but not for HTTP error code status 404. It seems like HTTP 404 errors are handled by DispatcherServlet by default. Is it possible to change this behaviour?

And how can I catch 404 errors in my exception handler?


回答1:


If you want to get some dynamic content in your 404 page or any other error page, map the page to a controller in your spring context. For example, declare a controller named "404.htm" and try to request the page /404.htm to insure that it's working fine, then in your web.xml write the following :

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



回答2:


Try with this url http://blog.codeleak.pl/2013/04/how-to-custom-error-pages-in-tomcat.html

Explains how to create a controller to get the error and put parameters to whow them in the .jsp.



来源:https://stackoverflow.com/questions/5553719/spring-mvc-3-how-to-provide-dynamic-content-to-error-page-for-http-404-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!