1. 程式人生 > >java web 判斷客戶端裝置是否移動端

java web 判斷客戶端裝置是否移動端

以下是全部程式碼,僅供參考!

import java.util.regex.Matcher; import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

public class UserAgentUtils {               // \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);              /**      * 驗證是否為手機訪問      * @param request      * @return      */     public static boolean judgeIsPhone(HttpServletRequest request){         boolean _isPhone = false;         if(StringUtils.isNoneBlank(request.getHeader("User-Agent"))){             String _userAgent = request.getHeader("User-Agent").toLowerCase();             Matcher _matcherPhone = phonePat.matcher(_userAgent);             Matcher _matcherTable = tablePat.matcher(_userAgent);               if(_matcherPhone.find() || _matcherTable.find()){                 _isPhone = true;             }         }         return _isPhone;     } }