首页 > 代码库 > Servlet3.0中的异步请求

Servlet3.0中的异步请求

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中的异步请求