Servlet3的异步实现


         Servlet3 引入了一个新的特性,它可以让Servlet异步处理请求。请Servlet/JSP程序中有一个或者多个长时间运行的操作时,这项特性就特别好用。它会将那些分配给一个新的线程,从而将这个请求处理线程返回到线程池中,准备服务下一个请求。

         

package com.song.asycdemo;

import java.io.IOException;

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;

/**
 * 异步Servlet
 * 
 * @author 宋伟宁
 * 
 * @version 2014年11月24日上午10:53:41
 */
@WebServlet(name = "AsyncDispatcherServlet", urlPatterns = "/asynDispatch", asyncSupported = true)
public class AsyncDispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AsyncDispatcherServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * 多线程的实现
	 */
	protected void doGet(final HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		final AsyncContext asyncContext = request.startAsync();
		request.setAttribute("mess", Thread.currentThread().getName());
		asyncContext.setTimeout(5000);
		asyncContext.start(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(3000);
					
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				request.setAttribute("ww", Thread.currentThread().getName());
				asyncContext.dispatch("/threadNames.jsp");
			}
		});

	}

}
              以上的代码中,它的长时间任务,我们简化为休眠3秒钟,为了验证长时间运行的任务是主线程(执行doGet方法)以外的其它线程中执行的,在Servlet中添加了主线程的名称,并将它们发送到jsp页面中。

     测试页面代码:

<body>

   主线程:${mess}
   工作线程:${ww}
</body>

 执行效果:

   

猜你喜欢

转载自blog.csdn.net/tonysong111073/article/details/41442369