根据User-Agent,获得客户端浏览器和操作系统的信息

最近做项目中,我碰到取客户端浏览器和操作系统信息的问题,网上找了很久,大多都是在页面中嵌入JS实现的,无法满足我的要求。所以,就自己写了个方法,可以在servlet中取到。我是根据每个浏览器User-Agent的特征,来判断的。(在windows xp中已测)

DemoServlet.java

 doPost方法中

String userAgent = request.getHeader("User-Agent");
ClientInfo clientInfo = ClientInfoUtil.getClientInfo(userAgent);
String userBrowser = clientInfo.getBrowserInfo();/** 得到用户的浏览器信息 */
String userOS = clientInfo.getOsInfo();/** 得到用户的操作系统信息 */


ClientInfoUtil.java

/**
* @author 林水镜, E-mail:shuijing.linshj@alibaba-inc.com
* @create 2008-9-17 上午09:57:35
*/
public class ClientInfoUtil {

/**
* 根据User-Agent,得到用户浏览器和操作系统信息
*
* @param userAgentInfo
* @return ClientInfo
*/
public static ClientInfo getClientInfo(String userAgentInfo) {
String info = userAgentInfo.toUpperCase();
ClientInfo clientInfo = new ClientInfo();
String[] strInfo = info.substring(info.indexOf("(") + 1,
info.indexOf(")") - 1).split(";");
if ((info.indexOf("MSIE")) > -1) {
clientInfo.setBrowserInfo(strInfo[1].trim());
clientInfo.setOsInfo(strInfo[2].trim());
} else {
String[] str = info.split(" ");
if (info.indexOf("NAVIGATOR") < 0 && info.indexOf("FIREFOX") > -1) {
clientInfo.setBrowserInfo(str[str.length - 1].trim());
clientInfo.setOsInfo(strInfo[2].trim());
} else if ((info.indexOf("OPERA")) > -1) {
clientInfo.setBrowserInfo(str[0].trim());
clientInfo.setOsInfo(strInfo[0].trim());
} else if (info.indexOf("CHROME") < 0
&& info.indexOf("SAFARI") > -1) {
clientInfo.setBrowserInfo(str[str.length - 1].trim());
clientInfo.setOsInfo(strInfo[2].trim());
} else if (info.indexOf("CHROME") > -1) {
clientInfo.setBrowserInfo(str[str.length - 2].trim());
clientInfo.setOsInfo(strInfo[2].trim());
} else if (info.indexOf("NAVIGATOR") > -1) {
clientInfo.setBrowserInfo(str[str.length - 1].trim());
clientInfo.setOsInfo(strInfo[2].trim());
} else {
clientInfo.setBrowserInfo("Unknown Browser");
clientInfo.setOsInfo("Unknown OS");
}
}
return clientInfo;
}
}


model
ClientInfo.java

/**
* 注册用户来源信息
* @author shuijing.linshj
*2008-9-18
*/
public class ClientInfo {
/** 浏览器信息 */
private String browserInfo;
/** 操作系统信息 */
private String osInfo;

public String getBrowserInfo() {
return browserInfo;
}

public void setBrowserInfo(String browserInfo) {
this.browserInfo = browserInfo;
}

public String getOsInfo() {
return osInfo;
}

public void setOsInfo(String osInfo) {
this.osInfo = osInfo;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值