Java判斷PC端還是移動端


package com.*.*.*;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* 檢測是否為移動端設備訪問
*/
public class IsModel {
// \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
* @param userAgent
* 瀏覽器標識
* @return true:移動設備接入,false:pc端接入
*/
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 {
return false;
}
}

/**
* 檢查訪問方式是否為移動端
*
* @Title: check
* @param request
* @throws IOException
*/
public static boolean check(HttpServletRequest request,
HttpServletResponse response) throws IOException {
boolean isFromMobile = false;
// 檢查是否已經記錄訪問方式(移動端或pc端)
try {
// 獲取ua,用來判斷是否為移動端訪問
String userAgent = request.getHeader("USER-AGENT").toLowerCase();
if (null == userAgent) {
userAgent = "";
}
isFromMobile = IsModel.check(userAgent);
// 判斷是否為移動端訪問
if (isFromMobile) {
System.out.println("移動端訪問");
return isFromMobile;
} else {
System.out.println("pc端訪問");
return isFromMobile;
}
} catch (Exception e) {
e.printStackTrace();
}
return isFromMobile;
}
}


免責聲明!

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



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