日期:2014-05-20 浏览次数:21022 次
@WebServlet(urlPatterns="/test",asyncSupported=true) public class ModuleAsyncServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setCharacterEncoding("UTF-8"); Writer out = response.getWriter(); // request.startAsync(); //报异常 AsyncContext ctx = request.getAsyncContext();//null System.out.println(request.isAsyncSupported()); //false
package org.async.servlet; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.Date; import javax.servlet.AsyncContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns="/test",asyncSupported=true) public class ModuleAsyncServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setCharacterEncoding("UTF-8"); Writer out = response.getWriter(); request.startAsync(); AsyncContext ctx = request.getAsyncContext(); System.out.println(request.isAsyncSupported()); //AsyncContext ctx = request.startAsync(); new Thread(new Executor(ctx)).start(); out.write("结束Servlet的时间:" + new Date() + "."); out.flush(); } catch (Exception e) { e.printStackTrace(); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } } class Executor implements Runnable { private AsyncContext ctx = null; public Executor(AsyncContext ctx) { this.ctx = ctx; } public void run() { try { // 等待十秒钟,以模拟业务方法的执行 Thread.sleep(10000); PrintWriter out = ctx.getResponse().getWriter(); out.println("业务处理完毕的时间:" + new Date() + "."); out.flush(); ctx.complete(); } catch (Exception e) { e.printStackTrace(); } } }