How do I tell what browser is hitting a servlet?
Author: Deron Eriksson
Description: This Java servlet tutorial describes how to use a request header's user-agent to tell what browser is hitting a servlet.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1 || Tomcat 5.5.20

Page: < 1 2

(Continued from page 1)

If we start our 'tomcat-demo' debug configuration in EclipseSW and then hit the TestServlet via the Internet Explorer 7 browser, we see the following result.

Hitting test servlet with IE7

Notice the 'user-agent' value. It tells us that the browser hitting the servletW is IE 7 and rather crypically that the platform is Windows XP.

If we hit our servlet in Firefox 2, we see the following:

Hitting test servlet with Firefox

Notice that the 'user-agent' value tells us that the version of the browser is Firefox and that once again the platform is Windows XP.

As you can see, it's easy to view the user-agent string, which can tell us information about the browser hitting our servlet and the platform on which the browser is running. However, user-agent strings can literally come in endless varieties, so a highly detailed analysis of the user-agent strings can be a challenge.

This can be very useful information if you write web applications on a company intranet, since it can tell you useful details about your user population. This can help you design you web applications to meet your audiences needs. It may help simplify your development process, since you can avoid writing code (ie, javascriptW) if your audience doesn't use a particular type of browser, which you figured out by looking at the user-agent strings. Additionally, if you really need to, you can use this browser information to write conditional code based on the type of browser hitting the servlet. For instance, if you site doesn't support Netscape 4.7 anymore, you could return a message saying that the user's browser isn't supported rather than returning the normal content.

As a side note, conditional code can also be embedded in Javascript so that the browser web page output or functionality may be different depending on the type of browser. This technique sends the conditional logic to the client (browser) in Javascript, whereas the user-agent analysis we examined in this tutorial places the conditional logic on the server in JavaSW.

Page: < 1 2