Detecting Which Browser In Java Servlet/Filter

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.

Related posts:

  1. 301 Redirects Made Easy In Java
  2. ResourceTransformFilter – DataUris, LessCSS, Javascript and CSS Compression Made Easy!
  3. HTML Sanitizer added to visural-common…
  4. Wicket – forcing page reload on browser back button…
  5. AOP, Annotation-based caching solution for Guice projects…

This entry was posted in Java, Software Engineering and tagged Java, open-source, visural-common. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>