@ControllerAdvice与ResourceHandler冲突:Spring 4

时间:2016-04-20 15:33:44

标签: java spring spring-mvc spring-4

我正在运行Spring 4 web mvc项目:

问题: 我的404异常处理程序的controlleradvice无法正常工作。但是,如果我在WebConfig类中注释“addResourceHandlers”方法,它将起作用。 (我无法删除它,因为它解析了我的静态资源)_

这是我的网络配置:

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    /*
     * Resource handler for static resources
     */
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
    }
}

这是我的404异常处理程序:

@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(NoHandlerFoundException.class)
    public String handle404(Exception e)   {
        return "error/404";
    }
}

1 个答案:

答案 0 :(得分:1)

如果您的网络应用程序使用web.xml,则非常简单 - 只需添加以下内容(假设使用 InternalResourceViewResolver ,前缀指向您的 WEB-INF 查看文件夹和后缀 .jsp )。您也可以拥有其他错误代码的多个错误页面元素。

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

如果你没有使用web.xml,那就有点复杂了。

如果你想抓住NoHandlerFound例外,首先要告诉Spring通过setting a flag in the DispatcherServlet directly抛出它。

为此,在您要扩展的类AbstractAnnotationConfigDispatcherServletInitializer中覆盖onStartup方法以公开DispatcherServlet定义并手动添加所需的标志:

@Override
public void onStartup(ServletContext servletContext) throws ServletException {

    //...
    WebApplicationContext context = getContext();
    DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
    //we did all this to set the below flag
    dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet",dispatcherServlet );
    //..
}

然后ExceptionController中的现有代码应该可以正常工作并拦截异常