解决Spring Boot自定义错误页导致文件无法上传的问题

网上的Spring Boot自定义错误页教程,基本上都是自己自定义一个ServletRegistrationBean,把DispatcherServlet里的setThrowExceptionIfNoHandlerFound设置为true,代码样例如下:

@Configuration
public class ErrorConfiguration {
    @Bean
    public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
        ServletRegistrationBean registration = new ServletRegistrationBean(
                dispatcherServlet);
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        return registration;
    }

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return (container -> {
            ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
            ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
            container.addErrorPages(error401Page, error404Page, error500Page);
        });
    }
}

但这种配置方式存在一个问题,我们自定义了ServletRegistrationBean之后,无法使用系统自带的DispatcherServletAutoConfiguration自动配置,于是缺少了很多配置,其中就包含上传文件所需要的配置。

解决方法很简单。只为了自定义错误页的话,根本无需像上面代码段中粗体部分那样自己自定义ServletRegistrationBean。直接在application.yml(或application.properties)里配置一句spring.mvc.throw-exception-if-no-handler-found: true,就可以把DispatcherServlet里的setThrowExceptionIfNoHandlerFound设置为true了。

发表评论

电子邮件地址不会被公开。 必填项已用*标注