Wednesday, February 23, 2011

Can you Directly get the Browser Name and Version in the JSP?

Hai Guys,

There is no direct way to the get the Browser Name and version in the JSP.

check the following program.

copy the following code inside a JSP page.
<%!
String browserName = "";
String browserVersion = "";
String tmpResult = "";
String getBrowserVersion(String ua, int index) {
tmpResult=ua.substring(index,ua.length());
String temp[]=tmpResult.split(" ");
return temp[0].replaceAll(";","");
}
%>
<%
String _ua = (String) request.getHeader("User-Agent");
System.out.println(_ua);
if (_ua.contains("MSIE")) {
browserName = "Microsoft Internet Explorer";
browserVersion = getBrowserVersion(_ua, _ua.indexOf("MSIE ")+5);
}
if (_ua.contains("Firefox")) {
browserName = "FireFox";
browserVersion = getBrowserVersion(_ua, _ua.indexOf("Firefox/") +8);
}
if (_ua.contains("Chrome") && _ua.contains("Safari")) {
browserName = "Google Chrome";
browserVersion = getBrowserVersion(_ua, _ua.indexOf("Chrome/") +7);
}
if (_ua.contains("Safari") && _ua.indexOf("Chrome")==-1) {
browserName = "Safari";
browserVersion = getBrowserVersion(_ua, _ua.indexOf("Version/") +8);
}
out.print("BrowserName  : " + browserName + "<br>");
out.print("BrowserVersion  : " + browserVersion);
 %>
out put

BrowserName : FireFox
BrowserVersion : 3.6.13

 OR

 <%!     
String browserName = "";
String browserVersion = "";
String tmpResult = "";
String getBrowser(String ua, String splitcon, String name) {
String temp1[] = ua.split(splitcon);
for (String s : temp1) {
if(s.contains(name))
tmpResult = s.trim();
}
tmpResult = tmpResult.replaceAll(" ", "/");
String temp2[] = tmpResult.split("/");
return temp2[1];
}
%>
<%
String _ua = (String) request.getHeader("User-Agent");
if (_ua.contains("MSIE")) {
browserName = "Microsoft Internet Explorer";
browserVersion = getBrowser(_ua, ";", "MSIE");
}
if (_ua.contains("Firefox")) {
browserName = "FireFox";
browserVersion = getBrowser(_ua, " ", "Firefox");
}
if (_ua.contains("Chrome") && _ua.contains("Safari")) {
browserName = "Google Chrome";
browserVersion = getBrowser(_ua, " ", "Chrome");
}
if (_ua.contains("Safari") && _ua.indexOf("Chrome")==-1) {
browserName = "Safari";
browserVersion = getBrowser(_ua, " ", "Version");
}
out.print("BrowserName  : " + browserName + "<br>");
out.print("BrowserVersion  : " + browserVersion);
%>

OUT PUT

BrowserName : FireFox
BrowserVersion : 3.6.13

Thanks,

Keep Rocking.

No comments:

Post a Comment