You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot 2如何禁用ErrorPageFilter?解决响应已提交错误

解决Spring Boot部署Tomcat时的ErrorPageFilter报错问题

你遇到的这个错误提示确实让人头疼:

15:45:16.380 [http-nio-8080-exec-3] ERROR o.s.b.w.s.support.ErrorPageFilter - Cannot forward to error page for request [/] as the response has already been committed. As a result, the response may have the wrong status code. If your application is running on WebSphere Application Server you may be able to resolve this problem by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false

你已经尝试在SpringBootServletInitializer的构造函数里调用setRegisterErrorPageFilter(false),但可能因为部署场景或配置优先级的原因没生效,下面给你几个更稳妥的解决方案:

方案1:排除ErrorMvcAutoConfiguration自动配置

直接在你的@SpringBootApplication注解中排除错误相关的自动配置类,这样Spring Boot就不会注册ErrorPageFilter了:

@SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class})
@ComponentScan({ "a.b.c.*" })
public class AppWebApplication extends SpringBootServletInitializer {
    public AppWebApplication() {
        super();
        setRegisterErrorPageFilter(false);
    }
    public static void main(String[] args) {
        SpringApplication.run(AppWebApplication.class, args);
    }
}

方案2:用FilterRegistrationBean手动禁用ErrorPageFilter

这种方式更灵活,适合需要保留其他错误配置但只想禁用这个Filter的场景,创建一个配置类:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.support.ErrorPageFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean<ErrorPageFilter> disableErrorPageFilter() {
        FilterRegistrationBean<ErrorPageFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new ErrorPageFilter());
        registrationBean.setEnabled(false);
        return registrationBean;
    }
}

方案3:通过application.properties配置关闭(Spring Boot 2.x适用)

在src/main/resources/application.properties里加以下配置,直接阻止ErrorPageFilter的注册,同时也能避免白标错误页相关的问题:

# 关闭白标错误页,同时会影响ErrorPageFilter的注册
spring.mvc.error.whitelabel.enabled=false
# 可选:关闭异常信息和栈追踪的返回,进一步减少ErrorPageFilter的触发场景
server.error.include-exception=false
server.error.include-stacktrace=never

要是你需要自定义错误页,记得额外配置自己的错误处理逻辑(比如用@ControllerAdvice)。

额外要检查的点

  • 确认你的Tomcat版本和Spring Boot 2.2.1.RELEASE兼容,推荐用Tomcat 9.x,和这个Spring Boot版本匹配度更高
  • 检查你的控制器或拦截器里有没有提前调用response.flush()、response.getWriter().close()这类操作,这些会让响应提前提交,不仅会触发ErrorPageFilter的错误,本身也可能导致响应异常

试试上面的方法,应该能解决你的问题!

内容的提问来源于stack exchange,提问作者DevJavaJeeSpringBoot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:41:00