Servlet 3.0笔记之异步请求相关方法和AsyncContext转发
Start ..."); out.flush(); if (!request.isAsyncSupported()) { log.info("the servlet is not supported Async"); return; } request.startAsync(request, response); if (request.isAsyncStarted()) { AsyncContext asyncContext = request.getAsyncContext(); asyncContext.setTimeout(1L * 60L * 1000L);// 60sec new CounterThread(asyncContext).start(); } else { log.error("the ruquest is not AsyncStarted !"); } } private static class CounterThread extends Thread { private AsyncContext asyncContext; public CounterThread(AsyncContext asyncContext) { this.asyncContext = asyncContext; } @Override public void run() { int interval = 1000 * 20; // 20sec try { log.info("now sleep 20s, just as do some big task ..."); Thread.sleep(interval); log.info("now dispatch to another Async Servlet"); ServletRequest request = asyncContext.getRequest(); String disUrl = request.getParameter("disUrl"); if (StringUtils.isBlank(disUrl)) { disUrl = "/demoAsyncLink"; } if (disUrl.endsWith(".jsp")) { request.setAttribute("dateStr", DateFormatUtils.format( System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss")); } log.info("disUrl is : " + disUrl); // 将当前异步上下文所持有的request, response分发给Servlet容器 if (StringUtils.equals("self", disUrl)) { // 将分发到自身,即当前异步请求地址 asyncContext.dispatch(); } else { // 将分发到指定的路径 asyncContext.dispatch(disUrl); } } catch (InterruptedException e) { e.printStackTrace(); } } }}当前请求完成之后,将分发到下一个请求上面,若都是异步的Servlet,则很好的组成了异步Servlet请求链。有趣的地方在于,异步上下文环境可以分发到下一个异步或同步的servlet、jsp、html等资源。若访问类似于如下地址,当前URL永远不会断开,又一个永动机,除非网络链接出错或者服务器关闭。
http://localhost/servlet3/asyncDispatch2Async?disUrl=self上面的异步Servlet总是在不断的请求自我,成为了一个永动机;为disUrl传入要转发到的异步或同步的资源地址,组成一个链的模式,相当的简单轻松。
一个视图:
?