JSP DetectBrowser bean

Page content


A common problem with static content is that the web page’s layout and display differs between browsers, and often renders the page inaccessible or cluttered. With dynamic content, such difficulties can be overcome; we will particularly be focussing on how the Java Server Pages framework overcomes these difficulties.

It is possible to allow for content to be cross-compatible with different types of browsers by employing a ‘Javabean’, or a reusable object which can be called upon for a particular function. This is a class instance written in Java which conforms to a particular convention. In this case, we will be looking at writing the ‘DetectBrowser’ Bean, in order to detect the user’s browser which is helpful if you need to retrieve another page version from the server in case of difficulties.

‘DetectBrowser’ script

This coding example is courtesy of https://www.stardeveloper.com/. The site has great Java tutorials which are also helpful for beginners.

First create a file named DetectBrowser.java and place it in the appropriate directory related to your environment.

package com.stardeveloper.bean.test;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;

public final class DetectBrowser implements Serializable {

private HttpServletRequest request = null;

private String useragent = null;

private boolean netEnabled = false;

private boolean ie = false;

private boolean ns6 = false;

private boolean ns4 = false;

public void setRequest(HttpServletRequest req) {

request = req;

useragent = request.getHeader(“User-Agent”);

String user = useragent.toLowerCase();

if(user.indexOf(“msie”) != -1) {

ie = true;

} else if(user.indexOf(“netscape6”) != -1) {

ns6 = true;

} else if(user.indexOf(“mozilla”) != -1) {

ns4 = true;


if(user.indexOf(".net clr") != -1)

netEnabled = true;


public String getUseragent() {

return useragent;


public boolean isNetEnabled() {

return netEnabled;


public boolean isIE() {

return ie;


public boolean isNS6() {

return ns6;


public boolean isNS4() {

return ns4;



Now you can create a JSP page in order to test the above. Name your page DetectBrowser.jsp and use the following code:

<jsp:useBean id=“db” class=“com.stardeveloper.bean.test.DetectBrowser”


<jsp:setProperty name=“db” property=“request” value="<%= request %>" />


<jsp:getProperty name=“db” property=“useragent” />

<jsp:getProperty name=“db” property=“netEnabled” />

Internet Explorer - By far the best browser you can get.

<% } else if(db.isNS6()) { %>

Netscape 6 - If you cannot run Internet Explorer, use Netscape 6.

<% } else if(db.isNS4()) { %>

Netscape 4 - You have got to upgrade your browser!

<% } else { %>

Other - Your browser could not be detected by DetectBrowser Bean.

Please report to

[email protected]

and tell him this message that you got along with the User-Agent

string above.

<% } %>