【问题标题】:@ControllerAdvice conflict with ResourceHandler : Spring 4@ControllerAdvice 与 ResourceHandler 冲突:Spring 4
【发布时间】:2016-04-20 23:46:46
【问题描述】:

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

问题: 我的 404 异常处理程序的控制器建议不起作用。但是,如果我在 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";
    }
}

【问题讨论】:

    标签: java spring spring-mvc spring-4


    【解决方案1】:

    如果您的 webapp 使用 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 中的现有代码应该可以工作并拦截异常

    【讨论】:

    • 我已经在 onStartup 方法中将 throwExceptionIfNoHandlerFound 设置为 true,当我从 WebConfig 中删除“addResourceHandlers”方法时它可以工作。我不能同时使用它们。
    • 这可能是因为您设置了 registry.addResourceHandler("/**") ,其中包含所有内容。从你的资源位置来看,不能定义registry.addResourceHandler("/static/**") 来缩小静态内容吗?
    • :) 做到了。非常感谢。你能告诉我为什么会发生冲突吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2016-08-12
    • 2021-08-19
    • 2016-12-08
    • 2015-11-28
    • 2013-08-04
    • 1970-01-01
    相关资源
    最近更新 更多