首先要把tomcat7中的servlet-api.jar 和tomcat-api.jar 加到eclipse引用中,这样可以开发而打包的时候不会包含这两个jar,直接在tomcat7上跑
@WebServlet(name="Servlet3", urlPatterns={"/demo", "/servlet"},asyncSupported=true)//此为Servlet3新增的注解支持,asyncSupported=true表示支持异步
//也可在web.xml中添加<async-supported>true</async-supported>
public class Servlet3 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("下订单开始: " + new Date() + "<br/>");
out.flush();
AsyncContext ctx = req.startAsync();
//异步去执行开通订单
new Thread(new CheckOrder(ctx)).start();
out.println("订购成功: " + new Date()+ "<br/>");
out.flush();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
public class CheckOrder implements Runnable{
private AsyncContext ctx = null;
public CheckOrder(AsyncContext ctx) {
this.ctx = ctx;
}
public void run() {
try {
//模拟开通等待
Thread.sleep(3000);
PrintWriter out = ctx.getResponse().getWriter();
out.println("已经有权限了,let's go! : " + new Date() );
out.flush();
ctx.complete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果
下订单开始: Thu Jul 08 15:49:30 CST 2010
订购成功: Thu Jul 08 15:49:30 CST 2010
没有等待那个模拟开通就直接返回了,过了三秒在打印出
已经有权限了,let's go! : Thu Jul 08 15:49:33 CST 2010