码迷,mamicode.com
首页 > 其他好文 > 详细

Servlet3.0中的异步请求

时间:2017-06-11 19:11:38      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:his   UI   http   nts   tps   prot   sys   定义   pos   

package com.itheima.async;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet3.0中异步请求的servlet,相当于多线程
 */
@WebServlet(urlPatterns="/AsyncServlet",asyncSupported=true)
public class AsyncServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取异步的context对象
		AsyncContext context = request.startAsync(request, response);
		//传一个线程
		context.start(new MyRunnable(context) );
		for(int i =1 ;i<=10; i++){
			
			System.out.println(i);
			try {
				Thread.sleep(400);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
//定义一个线程
class MyRunnable implements Runnable{
	private AsyncContext context;

	public MyRunnable(AsyncContext context) {
		this.context = context;
	}

	@Override
	public void run() {
		for(char i=‘a‘; i<= ‘z‘; i++){
			try {
				context.getResponse().getWriter().println(i);
				Thread.sleep(100);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	
	
}

  

Servlet3.0中的异步请求

标签:his   UI   http   nts   tps   prot   sys   定义   pos   

原文地址:http://www.cnblogs.com/csic/p/6985801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!