日期:2014-05-18 浏览次数:20885 次
@WebServlet(urlPatterns="/asyncPrint",asyncSupported = true)
public class LoginServlet extends HttpServlet
{
private static final long serialVersionUID = -1428172087125899118L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html;charset=UTF-8");
AsyncContext async = req.startAsync();
new CounterThread(async).start();
}
}
class CounterThread extends Thread{
private AsyncContext asyncContext;
public CounterThread(AsyncContext asyncContext){
this.asyncContext = asyncContext;
}
public void run() {
if(asyncContext == null){
System.out.println(asyncContext);
return;
}
try
{
PrintWriter writer= asyncContext.getResponse().getWriter();
for( int i=0;i<50;i++)
{
int rand = new Random().nextInt(10)*1000;
printPage(writer,"this print is " + rand);
Thread.sleep(rand);
}
writer.close();
}catch(Exception e){
e.printStackTrace();
}
}
private void printPage(PrintWriter writer,String str)
{
writer.write("<h1>" + str + "</h1>");
writer.flush();
}
}