如何处理静态资源中发生的异常?

时间:2017-04-02 09:21:52

标签: java spring-mvc

我在静态资源中遇到spring mvc异常处理问题。

这是我的webInitializer类

protected String[] getServletMappings() {
    return new String[]{"/"};
}

protected Class<?>[] getRootConfigClasses() {
    return new Class<?>[] { RootConfig.class};
}

protected Class<?>[] getServletConfigClasses() {
    return new Class<?>[] {WebConfig.class};
}

@Override
protected FrameworkServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
    DispatcherServlet dispatcherServlet = new DispatcherServlet(servletAppContext);
    dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
    return dispatcherServlet;
}

和webConfig类:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "main.spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter{

@Bean
public ViewResolver viewResolver() {
    InternalResourceViewResolver resolver =
            new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    resolver.setExposeContextBeansAsAttributes(true);
    return resolver;
}

@Bean
public MultipartResolver multipartResolver(){
    return new StandardServletMultipartResolver();
}


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resource/**")
            .addResourceLocations("/resource/");

}
}

和ExceptionHandler类:

@ControllerAdvice
public class ExceptionController {

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

当找不到页面异常并且我的自定义404显示但是当请求出现错误的静态资源(如http://localhost:8080/resource/3,异常处理程序无法正常工作且结果页面如下所示)时,每件事情都能正常工作:

link

如何为静态资源启用异常处理程序? 抱歉英语不好。

0 个答案:

没有答案