日期:2014-05-18  浏览次数:20885 次

AsyncContext异步输出报错:java.lang.NullPointerException

@WebServlet(urlPatterns="/asyncPrint",asyncSupported = true)
public class LoginServlet extends HttpServlet 
{
private static final long serialVersionUID = -1428172087125899118L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletExceptionIOException 
{
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();
    }
}


每次调用,都报错:
java.lang.NullPointerException
at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:215)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:480)
at org.apache.coyote.http11.InternalOutputBuffer.flush(InternalOutputBuffer.java:119)
at org.apache.coyote.http11.AbstractHttp11Processor.action(AbstractHttp11Processor.java:799)
at org.apache.coyote.Response.action(Response.java:174)
at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:366)
at org.apache.catalina.connector.OutputBuffer.flush(OutputBuffer.java:333)
at org.apache.catalina.connector.CoyoteWriter.flush(CoyoteWriter.java:98)
at cn.cloud.action.CounterThread.printPage(LoginServlet.java:69)
at cn.cloud.action.CounterThread.run(LoginServlet.java:53)
五月 02, 2014 10:03:16 上午 org.apache.catalina.core.StandardContext reload
信息: Reloading Context with name [/jshop] has started
五月 02, 2014 10:03:16&