<error-page>设置在Spring MVC中不起作用

hin*_*531 7 java spring spring-mvc

问题

我想向用户显示自定义错误页面.Simeply说,<error-page>在web.xml上似乎没有用.我可以猜到问题是什么,但我需要了解为什么它不起作用.


我的设置

<error-page>在我的spring mvc应用程序中设置了web.xml.以下是设置.

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
    <url-pattern>*.*</url-pattern>
    <url-pattern>*.do</url-pattern>     
</servlet-mapping>

<error-page>
    <error-code>404</error-code>
    <location>/error</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)

我的错误页面就在...

WEB-INF
?   views
    ?   Errorpages
        ?   ErrorPage.jsp
Run Code Online (Sandbox Code Playgroud)

对于你的信息,我也尝试过以下这些东西,但这些都没有用.

<error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/Errorpages/ErrorPage.jsp</location>
</error-page>

<error-page>
    <error-code>404</error-code>
    <location>/views/Errorpages/ErrorPage.jsp</location>
</error-page>

<error-page>
    <error-code>404</error-code>
    <location>/Errorpages/ErrorPage.jsp</location>
</error-page>

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

<!-- Or tried those above without the .jsp that comes after ErrorPage -->
<!-- And also, tried those after moving the resources out of WEB-INF -->
Run Code Online (Sandbox Code Playgroud)

第二个尝试

我看了一下服务器日志,发现spring试图通过redirecion来查找资源,所以我改变了我的计划并试图通过典型的视图返回来实现这个目标Spring MVC.

我做了这个动作

@RequestMapping("/error")
public String throwsErrorPage(Locale locale, Model model) {
    logger.info("Errorpage action..." + locale.getLanguage());              
    return "/Errorpages/ErrorPage";
}
Run Code Online (Sandbox Code Playgroud)

我所期待的部分是正确的,因为它成功地称之为行动.我的服务器日志清楚地说明了.

WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/notfound] in DispatcherServlet with name 'appServlet'
INFO : com.company.web.controller.HomeController - Errorpage action...ko
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我通过在url上键入notfound来生成404错误,并且重定向到/<location>在web.xml中指定的错误.但它不会返回视图.

为了确保操作返回视图,我尝试更改操作的类型,如...

@RequestMapping("/error")
public ModelAndView throwsErrorPage(Locale locale, ModelAndView mv) {
    logger.info("Errorpage action..." + locale.getLanguage());              
    return mv.setViewName("/Errorpages/ErrorPage");
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用......


奇怪的事情

如果我通过localhost:8080/error它调用操作肯定会调用该操作并返回预期的错误页面.那么通过在url或ajax上键入内容,重定向和典型请求之间应该存在一些差异.


我想知道什么

  1. 如何进行<error-page>配置工作?
  2. 自动重定向Spring与用户操作的典型请求之间的区别是什么Spring MVC

小智 0

<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)

错误页面可能没有放入web-inf,移出多多尝试