java判断访问方式是手机端还是电脑端的工具类
检查访问方式是手机端还是电脑端的工具类
对request请求头,user-agent的值进行正则判断
import java.util.regex.Matcher;
import java.util.regex.Pattern;/**
- 检测是否为移动端设备访问
- @author Administrator
/
public class CheckMobile {
//手机
static String phoneReg="\\b(ip(hone|od)|android|opera m(ob|in)i"
+"|windows (phone|ce)|blackberry"
+"|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
+"|laystation portable)|nokia|fennec|htc[-_]"
+"|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
//平板
static String tableReg="\\b(ipad|tablet|(Nexus 7)|up.browser"
+"|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
//移动设备正则表达式匹配:手机端、平板
static Pattern phonePat =Pattern.compile(phoneReg,Pattern.CASE_INSENSITIVE);
static Pattern tablePat =Pattern.compile(tableReg,Pattern.CASE_INSENSITIVE);
public static boolean check(String userAgent){
if(null==userAgent){
userAgent="";
}
//开始匹配
Matcher matcherPhone=phonePat.matcher(userAgent);
Matcher matcherTable=tablePat.matcher(userAgent);
if(matcherPhone.find()||matcherTable.find()){
//移动设备入口
return true;
}else{
//pc端入口
return false;
}
}
}
2.调用
/**
* 检查访问方式
*/
public void checkEquipment(HttpServletRequest request,HttpServletResponse response){
String ua=(String) session.getAttribute(request,"ua");
if(null==ua){
try{
String userAgent = request.getHeader( "USER-AGENT" ).toLowerCase();
if(null == userAgent){
userAgent = "";
}
if(CheckMobile.check(userAgent)){
ua="mobile";
} else {
ua="pc";
}
session.setAttribute(request, response, "ua",ua);
}catch(Exception e){}
}
if(StringUtils.isNotBlank((ua) )){
request.setAttribute("ua", ua);
}
}
还没有评论,来说两句吧...