Java Reference
In-Depth Information
while (is.isReady()
&& (len = is.read(b)) != -1) {
String data = new String(b, 0, len);
System.out.println(data);
}
} catch (IOException ex) {
Logger.getLogger(ReadListenerImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void onAllDataRead() {
context.complete();
}
@Override
public void onError(Throwable thrwbl) {
System.out.println("Error: " + thrwbl);
// perform cleanup here
context.complete();
}
}
The AsyncContext.complete method is called in the onAllDataRead method to indicate that the read has been
completed and to commit the response. This method is also called in the onError implementation so that the read
will complete, so it is important to perform any cleanup within the body of the onError method to ensure that no
resources are leaked.
Similarly, a WriteListener implementation can use the new ServletOutputStream.canWrite method, which
determines whether data can be written in a nonblocking manner. A WriteListener implementation class must
override a couple of methods: onWritePossible and onError . The onWritePossible method is invoked when a
nonblocking write can occur. The write implementation should take place within the body of this method. The
onError method is much the same as its ReadListener implementation counterpart, because it is invoked when an
error occurs.
The following lines of code demonstrate how to register a WriteListener with a ServletOutputStream :
AsyncContext context = request.startAsync();
ServletOutputStream os = response.getOutputStream();
os.setWriteListener(new WriteListenerImpl(os, context));
As mentioned previously, the WriteListener implementation class must include overriding methods
for onWritePossible and onError , as shown in the next example. The following sources are that of the
org.javaee7.chapter01.WriteListenerImpl class.
import javax.servlet.AsyncContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
 
Search WWH ::




Custom Search