900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 两种方法判断是否为移动端访问 跳转到对应wap页面

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

时间:2023-06-14 01:17:07

相关推荐

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

随着移动互联网的迅猛发展,越来越多的用户选择使用移动端浏览器访问网页。当用户访问一个网站的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 = pile(phoneReg, Pattern.CASE_INSENSITIVE); static Pattern tablePat = pile(tableReg, Pattern.CASE_INSENSITIVE); /** * 检测是否是移动设备访问 * * @Title: check * @Date : -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; }

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。