`
tjukk
  • 浏览: 42351 次
  • 性别: Icon_minigender_1
  • 来自: 天津
社区版块
存档分类
最新评论

两种方法判断是否为移动端访问,跳转到对应wap页面

    博客分类:
  • web
阅读更多

    随着移动互联网的迅猛发展,越来越多的用户选择使用移动端浏览器访问网页。当用户访问一个网站的pc端页面的时候,往往是非常影响用户体验的。我们希望当用户使用移动端浏览器访问我们的pc端网站的时候,自动跳转到对应的wap页面。本文主要介绍两种方法,分别在服务端和客户端判断是否为移动端访问并跳转。废话少说,上代码!

    一、服务端判断 Java代码如下:

package com.ky620.util;  
  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
  
public class CheckMobile {  
      
    // \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 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;    
        }    
    }  
}  

     二、移动端判断 JavaScript代码如下:

function checkMobile(){  
    var isiPad = navigator.userAgent.match(/iPad/i) != null;  
    if(isiPad){  
        return false;  
    }  
    var isMobile=navigator.userAgent.match(/iphone|android|phone|mobile|wap|netfront|x11|java|opera mobi|opera mini|ucweb|windows ce|symbian|symbianos|series|webos|sony|blackberry|dopod|nokia|samsung|palmsource|xda|pieplus|meizu|midp|cldc|motorola|foma|docomo|up.browser|up.link|blazer|helio|hosin|huawei|novarra|coolpad|webos|techfaith|palmsource|alcatel|amoi|ktouch|nexian|ericsson|philips|sagem|wellcom|bunjalloo|maui|smartphone|iemobile|spice|bird|zte-|longcos|pantech|gionee|portalmmm|jig browser|hiptop|benq|haier|^lct|320x320|240x320|176x220/i)!= null;  
    if(isMobile){  
        return true;  
    }  
    return false;  
} 

 

    举个栗子:当用户使用移动端访问这个页面 http://www.ky620.com/info/253556 时,将会自动跳转到 http://wap.ky620.com/info/253556 。

 

2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics