Servlet3.0中的异步请求

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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中的异步请求的主要内容,如果未能解决你的问题,请参考以下文章

Servlet3.0对异步处理的支持

Servlet3.0的异步

servlet3.0 新特性——异步处理

关于servlet3.0中的异步servlet

[tomcat]源码简析 异步/非阻塞和请求构成

[tomcat]源码简析 异步/非阻塞和请求构成