java判斷是移動端還是pc端


// \b 是單詞邊界(連着的兩個(字母字符 與 非字母字符) 之間的邏輯上的間隔),
// 字符串在編譯時會被轉碼一次,所以是 "\\b"
// \B 是單詞內部邏輯間隔(連着的兩個字母字符之間的邏輯上的間隔)
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);

/**
* 檢測是否是移動設備訪問
*
* @Title: check
* @Date : 2014-7-7 下午01:29:07
* @param userAgent 瀏覽器標識
* @return true:移動設備接入,false:pc端接入
*/
public static boolean checked(String userAgent){
if(null == userAgent){
userAgent = "";
}
// 匹配
Matcher matcherPhone = phonePat.matcher(userAgent);
Matcher matcherTable = tablePat.matcher(userAgent);
if(matcherPhone.find() || matcherTable.find()){
return true;
} else {
return false;
}
}
/**
* 檢查訪問方式是否為移動端
*
* @Title: check
* @Date : 2014-7-7 下午03:55:19
* @param request
* @throws IOException
*/
@SuppressWarnings("static-access")
public boolean check(HttpServletRequest request,HttpServletResponse response) throws IOException{
boolean isFromMobile=false;

HttpSession session= request.getSession();
//檢查是否已經記錄訪問方式(移動端或pc端)
if(null==session.getAttribute("ua")){
try{
//獲取ua,用來判斷是否為移動端訪問
String userAgent = request.getHeader( "USER-AGENT" ).toLowerCase();
if(null == userAgent){
userAgent = "";
}
isFromMobile=this.checked(userAgent);
//判斷是否為移動端訪問
if(isFromMobile){
session.setAttribute("ua","mobile");
} else {
session.setAttribute("ua","pc");
}
}catch(Exception e){}
}else{
try{
//獲取ua,用來判斷是否為移動端訪問
String userAgent = request.getHeader( "USER-AGENT" ).toLowerCase();
if(null == userAgent){
userAgent = "";
}
isFromMobile=this.checked(userAgent);
//判斷是否為移動端訪問
if(isFromMobile){
session.setAttribute("ua","mobile");
} else {
session.setAttribute("ua","pc");
}
}catch(Exception e){}
isFromMobile=session.getAttribute("ua").equals("mobile");
}
return isFromMobile;
}

 

if(check(request, response)){
            mv.setViewName("phone/index");
        }else{
            mv.setViewName("page/index");
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM