该段代码代码显示了不使用异步处理的基本servlet:
@WebServlet(urlPatterns={"/syncservlet"})
public class SyncServlet extends HttpServlet {
private MyRemoteResource resource;
@Override
public void init(ServletConfig config) {
resource = MyRemoteResource.create("config1=x,config2=y");
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
String param = request.getParameter("param");
String result = resource.process(param);
/* ... print to the response ... */
}
}
下面的代码使用异步处理显示同一servlet:
@WebServlet(urlPatterns={"/asyncservlet"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet {
/* ... Same variables and init method as in SyncServlet ... */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
final AsyncContext acontext = request.startAsync();
acontext.start(new Runnable() {
public void run() {
String param = acontext.getRequest().getParameter("param");
String result = resource.process(param);
HttpServletResponse response = acontext.getResponse();
/* ... print to the response ... */ acontext.complete();
}
}
区别:
AsyncServlet 添加了asyncSupported=true是属于 @WebServlet 注释的。
1、request.startAsync()使 request 请求使异步处理; response 在 service方法结束后没有发送到客户端。
2、acontext.start(new Runnable() {...}) 从容器中获取一个新线程。
3、内部类的run()方法的代码在新线程执行。内部类可以访问异步上下文以从请求读取参数并写入响应。调用异步上下文的方法有complete()响应发送给客户端。