Update: Invoke WebConnection#close when there is an error.

Servlet 3.1 Specification (JSR 340) is almost ready for the release. One of the new features is the support for protocol upgrade. HTTP protocol upgrade was introduced in HTTP 1.1 (RFC 2616):

The Upgrade general-header allows the client to specify what additional communication protocols it supports and would like to use if the server finds it appropriate to switch protocols. The server MUST use the Upgrade header field within a 101 (Switching Protocols) response to indicate which protocol(s) are being switched.
And Web Socket is an example of protocol upgrade. In Servlet 3.1,javax.servlet.http.HttpUpgradeHandler is introduced to allow the protocol upgrade processing. In this blog, I will illustrate the use of the new API with a hypothetical protocol of checking ISBN number as follows: 
Client: (a_isbn_to_be_verified)*|EXIT and tokens can be separated by " \t\n\r\f". Server: (a_previous_isbn (true|false) CRLF)*
In this example, TestServlet decides to upgrade to a "isbn" protocol. @WebServlet("/test") public class TestServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { // checking the upgrade header and decide to upgrade if ("isbn".equals(req.getHeader("Upgrade"))) { // send 101 status code and corresponding headers res.setStatus(101); res.setHeader("Upgrade", "isbn"); res.setHeader("Connection", "Upgrade"); ISBNHttpUpgradeHandler handler = req.upgrade(ISBNHttpUpgradeHandler.class); // we can custom the http upgrade handler handler.setDebug(true); } else { res.getWriter().println("No upgrade: " + req.getHeader("Upgrade")); } } } Note that we can use CDI injection and JNDI lookup in methods of HttpUpgradeHandler. The implementation ofISBNHttpUpgradeHandler is as follows: public class ISBNHttpUpgradeHandler implements HttpUpgradeHandler { // we can use CDI injection in HttpUpgradeHandler! @Inject private ISBNValidator isbnValidator; private boolean debug = false; public ISBNHttpUpgradeHandler() { } @Override public void init(WebConnection wc) { System.out.println("ISBNHttpUpgradeHandler.init"); try { if (debug) { // testing: JNDI lookup works in here, too InitialContext initialContext = new InitialContext();