首页 > 代码库 > 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中的异步请求
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。