Servlet 3.0 异步 不异步,错在哪里?
package com.servlet; import java.io.PrintWriter; import java.util.Date; import javax.servlet.AsyncContext; /** * * @author Administrator */ public class ProcessTask implements Runnable{ private AsyncContext ctx = null; public ProcessTask(AsyncContext ctx) { this.ctx = ctx; } @Override public void run() { try { //等待十秒钟,以模拟业务方法的执行 Thread.sleep(1000); PrintWriter out = ctx.getResponse().getWriter(); out.println("业务处理完毕的时间:" + new Date() + ".<br/>"); out.flush(); ctx.complete(); } catch (Exception e) { } } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.AsyncContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.annotation.WebServlet; /** * * @author Administrator */ @WebServlet(asyncSupported=true,urlPatterns={"/async"} ,name="Async Server") public class AsyncDemoServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } protected void process(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException { PrintWriter out = null; try { resp.setContentType("text/html;charset=UTF-8"); out = resp.getWriter(); out.println("进入Servlet的时间:" + new Date() + ".<br/>"); out.flush(); //在子线程中执行业务调用,并由其负责输出响应,主线程退出 boolean asyncSupported = req.isAsyncStarted(); out.println("是否支持异步:" + asyncSupported + ".<br/>"); out.flush(); if(asyncSupported){ AsyncContext ctx = req.startAsync(); ctx.start(new ProcessTask(ctx)); } out.println("结束Servlet的时间:" + new Date() + ".<br/>"); out.flush(); } catch (IOException ex) { } finally { out.close(); } } } 其中一句 boolean asyncSupported = req.isAsyncStarted(); 返回false。 其表示不支持 异步 吗? 测试容器为 Apache Tomcat/7.0.21, GlassFish Server 3.1.1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
isAsyncStarted
根据方法名可以知道这个方法的主要目的是是否开始异步任务
asyncSupported
根据的变量名,我们可以知道,你需要的是,是否支持异步
聪明的小伙伴,你发现什么了吗?
楼主自己没注意,你调用的方法是isAynsStarted(),而调用的时候又是在req.startAysnc()方式之前.....楼主是意思应该是调用isAynsSupported()才对