我如果想异步向页面输出,则可以使用Servlet3中的AsyncContext。也可以在Servlet中另外启动一个多线程处理,让主线程先返回页面
两种方式的代码如下
[code="java"]
public class ListServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.getWriter().println("I am begin output !");
response.getWriter().flush();
//方式一
AsyncContext async = request.startAsync();
new AsyncOutput(async).start();
//方式二
new ThreadOutput(response).start();
response.getWriter().println("I am finash output !");
response.getWriter().flush();
}
}
class AsyncOutput extends Thread
{
private AsyncContext async;
public AsyncOutput(AsyncContext async)
{
this.async = async;
}
public void run()
{
try
{
Thread.sleep(3000);
async.getResponse().getWriter().println("I was three minutes late !");
async.getResponse().getWriter().flush();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
class ThreadOutput extends Thread
{
private HttpServletResponse response;
public ThreadOutput(HttpServletResponse response)
{
this.response = response;
}
public void run()
{
try
{
Thread.sleep(3000);
response.getWriter().println("I was three minutes late !");
response.getWriter().flush();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
[/code]
这两种效果是一样啊
既然如此,那还搞什么AsyncContext
AsyncContext有什么不一样的地方
以上两种使用方式,有什么区别?
求指点