Hot questions for Using Transmission Control Protocol in servlets


Scenario :

  1. Web application connecting to a java servlet. (Using embedded jetty)
  2. High latency request, example a report generation ( takes seconds)
  3. User can close the browser in between the http request response cycle.

Problem :

How to detect browser closed in between the request and response cycle, at the server side ?

Though the problem can be solved by using another request from the UI, I was wondering whether we could get the information from the communication protocol itself ? As HTTP is using TCP/IP as the base protocol, shouldn't we be able to detect this as a connection closed from the connection initiator side.

I went through the servlet apis and also the api used for configuring jetty server but couldn't find anything closely related.

Also went through these stackoverflow questions

  1. Java Servlet : How to detect browser closing?
  2. How to detect browser close at server side in

Any insights ?


You'll get an exception when you attempt to write to the servlet output stream / writer.



Your best bet is the user agent string that is in the header of all HTTP requests. You can access it via the HttpServletRequest like this:

String agent = request.getHeader("User-Agent");

It contains info like browser (client) name, browser version, OS, OS version etc. Although there is no guarantee that these will be complete and valid, but from the server you can't force the client to send complete and valid info about itself.

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
    Chrome/34.0.1847.131 Safari/537.36

This means (source):

Mozilla: MozillaProductSlice. Claims to be a Mozilla based user agent, which is only true for Gecko browsers like Firefox and Netscape. For all other user agents it means 'Mozilla-compatible'. In modern browsers, this is only used for historical reasons. It has no real meaning anymore

5.0: Mozilla version

Windows NT 6.1: Operating System: Windows 7

WOW64: (Windows-On-Windows 64-bit) A 32-bit application is running on a 64-bit processor

AppleWebKit: The Web Kit provides a set of core classes to display web content in windows

537.36: Web Kit build

KHTML: Open Source HTML layout engine developed by the KDE project

like Gecko: like Gecko...

Chrome: Name: Chrome

34.0.1847.131: Chrome version

Safari: Based on Safari

537.36: Safari build

User Agent string analysis

About analyzing user agent strings: Looking for a Java User Agent String Parser

Also has an API.

And there are more on the internet (Google it).