java - SimpleMappingExceptionResolver 无法解析 404

标签 java spring-mvc exception modelandview

下面是我的 spring 配置文件:

<bean class="com.web.handler.CustomSimpleMappingExceptionResolver" >
    <property name="exceptionMappings">
        <props>              
            <prop key="java.lang.Throwable">error</prop>
        </props>
    </property>
</bean>

CustomSimpleMappingExceptionResolver

public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver{
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {

    if(int a = 1)
        return new ModelAndView("ViewName1");
    else
        return new ModelAndView("ViewName2");
    }

我的web.xml没有错误页面。我希望根据我的逻辑在 resolveException() 中显示不同的 View 。

CustomSimpleMappingExceptionResolver 类中,如果出现 404,则不会调用 resolveException()

最佳答案

在web.xml中设置错误页面

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

您的错误页面将在打开后立即重定向。

<html>
    <head>
    <title>Your Page Title</title>
    <meta http-equiv="REFRESH" content="0;url=error.htm">
    </head>
    <body>
    </body>
</html>

Controller 中应该有一个请求映射来处理 error.htm 请求。

@RequestMapping(value={"/error.htm"})
    ModelAndView routToErrorHandler(HttpServletRequest request, HttpServletResponse response) {
//any logic for your themes
}

关于java - SimpleMappingExceptionResolver 无法解析 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8162700/

相关文章:

java - 如何使用 headless Activity 处理静默 SEND Intent

java - TestExecutionListener 的顺序

ajax - Spring 和 Spring MVC 3.0 AJAX 集成

java - Spring JPA hibernate 副本

java - 错误: main class logger.MainLogger not found or loaded

java - 使用 Java 有条件地访问同一级别的 JsonElements

java - Spring请求范围bean

java - spring boot无法解析html View

java - ArrayOutOfBounds 异常合并排序

java - 如何在 Jetty 中记录异常堆栈跟踪?