Blog About Contact

Detecting Which Browser In Java Servlet/Filter

Published Mon, 19 Jul 2010 • 4 comments

The newest version of my open source tools project, visural-common - 0.4, includes a new feature the com.visural.web.client.WebClient class.

The purpose of this class is simple -

User-Agent string goes in -> Browser, version and platform comes out.

The "User-Agent" string is a HTTP header property that is sent as part of the HTTP request. All common web browsers (and other HTTP clients, such as search engine crawlers) send predictable user agent strings which allow detection of the browser and operating system being used.

This makes it very easy to add conditional code to your server-side logic (in servlet filters or otherwise), such that you can customise the web experience for each platform and browser.

The usage of the class is very simple -

import com.visural.web.client.*;

class MyFilter implements Filter {
    ...
    public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc)
            throws IOException, ServletException
    {
        HttpServletRequest req = (HttpServletRequest) sr;
        WebClient client = WebClient.detect(req);
        if (client.getUserAgent().equals(UserAgent.IE)) {
            // do something for IE only
        } else if (client.getUserAgent().equals(UserAgent.FIREFOX) &&
                 client.getPlatform().equals(Platform.LINUX)) {
            // etc.
        }
    }
    ...
}

Currently it supports the detection of the following browsers, including version number -

    IE,
    FIREFOX,
    CHROME,
    OPERA,
    SAFARI,
    GOOGLEBOT,
    YAHOO_SLURP,
    MSNBOT

And will detect the following operating systems -

    MACOSX,
    WIN95,
    WIN98,
    WINNT,
    WIN2K,
    WINXP,
    WINVISTA,
    WIN7,
    LINUX,
    IOS, (iPhone, iPad, iPod Touch)
    ANDROID

There are certainly other solutions for this, but I wanted a simple, elegant implementation, that is optimised for the typical sort of logic that you want this for on the server side.

You can download version 0.4 of visural-common at google code and get started right away. It is licensed under the Apache 2.0 License.


About the Author

Richard Nichols is an Australian software engineer with a passion for making things.

Follow him on twitter or subscribe by RSS or email.

You might also enjoy reading -


Discuss / Comment

There are 4 comments.

Add a comment

  • {{e.error}}

Thanks for your comment!/

Required.
Valid email address required.
Required.
Posting message, please wait...