在实际开发中,如果Servlet接收的请求是需要操作IO流然后再通过IO流的结果来访问或者更新数据库的,那么这个耗时的操作就要放在异步中处理,然后Servlet先跳到一个等待页面,在这个页面中通过Ajax不断发送请求读取异步处理的结果,这样用户体验会比较好,那么Servlet实现异步处理只需要使用到Servlet3.0之后提供的AsyncContext对象,简单的使用方法如下:


@WebServlet(name = "AcyncServlet", urlPatterns = "/AcyncServletDemo", asyncSupported = true)
public class AcyncServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");

PrintWriter out = response.getWriter();
out.println("<h1>Servlet Do Post Start</h1>");
out.flush();

AsyncContext context = request.startAsync();
//开启线程
new AsyncThread(context).start();

out.println("<h1>Servlet Do Post End</h1>");
out.flush();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

class AsyncThread extends Thread {
private AsyncContext context;

public AsyncThread(AsyncContext context) {
this.context = context;
}

@Override
public void run() {
try {
Thread.sleep(2000);
PrintWriter out = context.getResponse().getWriter();
out.println("<h1>异步延时输出,这里可以进行一些耗时的操作</h1>");
out.flush();
context.complete();

} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}


在这里,我在注释配置中配置了想要的url-pattern,所以就不需要在web.xml中再次进行配置:


@WebServlet(name = "AcyncServlet", urlPatterns = "/AcyncServletDemo", asyncSupported = true)


要注意的是,必须设置

asyncSupported = true
<h1>Servlet Do Post Start</h1>