Spring MVC 3:如何提供动态内容到HTTP 404错误的错误页面? [英] Spring MVC 3: How to provide dynamic content to error page for HTTP 404 errors?

查看:159
本文介绍了Spring MVC 3:如何提供动态内容到HTTP 404错误的错误页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的:

我想向HTTP 404错误页面提供一个模型。我不想写一个在web.xml中指定的静态错误页面,而是要使用
异常控制器来处理HTTP 404错误。

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.

我做了什么:

从web.xml中删除错误页面标签:

Removed error page tag from web.xml:

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

并在我的AbstractController类中实现了以下异常处理程序方法:

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);
}

是什么?

它适用于查找异常,但不适用于HTTP错误代码状态404.默认情况下,似乎HTTP 404错误由DispatcherServlet处理。是否可以改变这种行为?

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?

我的异常处理程序如何捕获404错误?

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

推荐答案

如果要在404页面或任何其他错误页面中获取一些动态内容,请将页面映射到Spring环境中的控制器。
例如,声明一个名为404.htm的控制器,并尝试请求页面/404.htm确保它正常工作,
然后在您的web.xml中写下如下内容:

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>

这篇关于Spring MVC 3:如何提供动态内容到HTTP 404错误的错误页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆