java判斷訪問方式是手機端還是電腦端的工具類

檢查訪問方式是手機端還是電腦端的工具類

  1. 對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);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章