Servlet3.0新特性之异步请求实践

异步处理准许Servlet重新发起一条新线程区调用耗时的业务方法,可以避免等待。

Servlet3.0的异步处理时通过AsyncContext类来处理的,Servlet可以通过ServletRequest的如下两个方法开启异步调用,创建AsyncContext对象

AsyncContext   startAsync()

AsyncContext   startAsync(ServletRequest ,ServletResponse)

重复调用上面的方法将得到同一个AsyncContext对象。AsyncContext对象代表异步处理的上下文,它提供了一些工具方法,可以完成设置异步调用的超时时间,dispatch用于请求、启动后台线程、获取request、response对象等功能。


package com.xxx.action;

import java.io.IOException;
import java.io.PrintWriter;
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(name="async",urlPatterns="/async",asyncSupported=true)
public class AsyncServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=GBK");
		PrintWriter out=response.getWriter();
		out.println("异步调用示例");
		out.println("进入servlet的时间:"+new Date()+"
"); out.flush(); //创建AsyncContext,开始异步调用 AsyncContext actx=request.startAsync(); //设置异步调用的超时时间 actx.setTimeout(30*1000); //启动异步调用的线程 actx.start(new Executor(actx)); out.println("结束servlet的时间:"+new Date()+"
"); out.flush(); } }


package com.xxx.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.AsyncContext;
import javax.servlet.ServletRequest;

public class Executor implements Runnable {

	private AsyncContext actx=null;
	
	public Executor() {
	}

	public Executor(AsyncContext actx) {
		super();
		this.actx = actx;
	}


	@Override
	public void run() {
		try {
			Thread.sleep(5*1000);
			ServletRequest request=actx.getRequest();
			List books=new ArrayList();
			books.add("book1");
			books.add("book2");
			request.setAttribute("books", books);
			actx.dispatch("/async.jsp");
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}


<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>



  
    My JSP 'async.jsp' starting page
  
  
  
  • ${book}
<% out.println("业务调用结束的时间:"+new java.util.Date()); //完成异步调用 request.getAsyncContext().complete(); %>


为servlet开启异步调用有两种方式:

@WebServlet指定asyncSupported=true

在web.xml文件的元素中添加子元素


通过web.xml文件中配置

 
 	async
 	com.xxx.action.AsyncServlet
 	
 	true
 
 
 	async
 	/async
 
   








你可能感兴趣的:(Servlet3.0新特性之异步请求实践)