Servlet3.0 对异步处理的支持

AsyncServlet.java

package sadhu;
import javax.servlet.annotation.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
import sadhu.Executor.*;
/*
Servlet异步处理类
*/
@WebServlet(urlPatterns={"/async"},asyncSupported=true)
public class AsyncServlet extends HttpServlet
{
	@Override
	public void doGet(HttpServletRequest request,HttpServletResponse response)
	throws IOException,ServletException
	{
		System.out.println("删除了!");
		response.setContentType("text/html;charset=GBK");
		PrintWriter out = response.getWriter();
		out.println("<title>异步调用示例</title>");
		out.println("进入Servlet的时间" + new Date()+".<br/>");
		out.flush();
		AsyncContext actx = request.startAsync();//创建异步对象
		actx.addListener(new MyAsyncListener());
		actx.setTimeout(30*1000);//设置超时
		actx.start(new Executor(actx));//开始启动异步调用的线程
		out.println("结束Servet的时间"+ new Date()+".</br>");
		out.flush();
	}
}
/**
执行类
*/
class Executor implements Runnable
{
	private AsyncContext actx = null;
	public Executor(AsyncContext actx)
	{
		this.actx = actx;
	}
	public void run()
	{
		try
		{
			Thread.sleep(5*1000);
			ServletRequest request = actx.getRequest();
			List<String> books = new ArrayList<String>();
			books.add("java");
			books.add("servlet 3.0");
			request.setAttribute("books",books);
			actx.dispatch("/async.jsp");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
/**
	监听异步执行方法,总共有四个方法
*/
class MyAsyncListener implements AsyncListener
{
	public void onComplete(AsyncEvent event)throws IOException
	{
		System.out.println("--------异步调用完成-----"+new Date());
	}
	public void onError(AsyncEvent event)throws IOException
	{
		
	}
	public void onStartAsync(AsyncEvent event)
	throws IOException
	{
		
	}
	public void onTimeout(AsyncEvent event)
	throws IOException
	{
		
	}
}

async.jsp

<%@ page contentType="text/html;charset=GBK" language="java" session="false" %>
<%@ page import="java.util.*" %>
<%
	if(request.getAttribute("books")!=null)
	{
		List<String> books = (List<String>)request.getAttribute("books");
		for(String item : books)
		{
			out.println(item+"<br/>");
		}
	}
	//request.getAsyncContext().complete();//完成异步调用
%>


你可能感兴趣的:(Servlet3.0 对异步处理的支持)