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.
时间: 2025-04-01 20:09:54 浏览: 55
### 启用Servlet和过滤器中的异步支持
#### 通过`web.xml`配置方式
为了在传统的基于XML的部署描述符中启用异步支持,可以在`<servlet>`或`<filter>`标签下添加子元素`<async-supported>true</async-supported>`。此设置告知容器该Servlet或Filter可以参与异步操作[^1]。
```xml
<servlet>
<servlet-name>AsyncExampleServlet</servlet-name>
<servlet-class>com.example.AsyncExampleServlet</servlet-class>
<async-supported>true</async-supported>
</servlet>
<filter>
<filter-name>AsyncExampleFilter</filter-name>
<filter-class>com.example.AsyncExampleFilter</filter-class>
<async-supported>true</async-supported>
</filter>
```
上述配置表明`AsyncExampleServlet`和`AsyncExampleFilter`都启用了异步支持。
---
#### 使用Java代码实现异步支持
除了通过`web.xml`声明外,还可以利用Servlet API动态启用异步功能。这通常涉及调用`HttpServletRequest.startAsync()`方法来启动异步上下文,并确保Servlet类实现了`javax.servlet.annotation.WebServlet`注解并设置了属性`asyncSupported=true`。
以下是具体的代码示例:
```java
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/async", asyncSupported = true)
public class AsyncExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 开始异步处理
final var asyncContext = req.startAsync();
new Thread(() -> {
try {
// 模拟耗时任务
Thread.sleep(5000);
// 设置响应内容
resp.setContentType("text/plain");
resp.getWriter().write("Asynchronous processing completed!");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// 完成异步请求
asyncContext.complete();
}
}).start();
}
}
```
在此示例中,`@WebServlet`注解的`asyncSupported`参数被显式设为`true`,表示允许异步执行。此外,在`doGet`方法内部调用了`req.startAsync()`以创建一个新的异步上下文。
对于过滤器而言,同样可以通过实现`javax.servlet.Filter`接口并在其初始化阶段指定`async-supported`特性来完成相同的功能。
---
#### 注意事项
当使用异步模式时,需要注意以下几点:
- 如果未正确结束异步操作(即未调用`asyncContext.complete()`),可能会导致连接保持打开状态直到超时。
- 需要确保所有参与异步流程的对象线程安全,因为它们可能由不同的线程访问。
- 异步支持仅适用于运行于Servlet 3.0及以上版本规范的容器环境中。
---
阅读全文
相关推荐













