【已解决】ex = ‘Async support must be enabled on a servlet and for all filters involved in async request

报错:

ex = 'Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "<async-supported>true</async-supported>" to servlet and filter declarations in web.xml.'

java.lang.IllegalStateException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "<async-supported>true</async-supported>" to servlet and filter declarations in web.xml.

原因:

该异常表明在处理异步请求时,servlet 或者相关过滤器没有开启异步支持。当使用 Spring 框架处理异步请求时,需要确保在 servlet 和过滤器配置中开启异步支持。

解决方案

如果你使用 Java 代码来配置 servlet 和过滤器,可以通过 ServletRegistration.Dynamic 和 FilterRegistration.Dynamic 类的 setAsyncSupported 方法来启用异步支持。示例如下:

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class AppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfig.class);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
        dispatcher.setAsyncSupported(true);

        // 配置过滤器并启用异步支持
        // FilterRegistration.Dynamic filter = servletContext.addFilter("someFilter", new SomeFilter());
        // filter.addMappingForUrlPatterns(null, false, "/*");
        // filter.setAsyncSupported(true);
    }
}