如何使用jsp正则判断是否是移动设备

看到了一篇很好的文章, 《在天猫,前端做什么?》,里面有天猫php判断移动设备的正则(个人猜测),觉得很好用,于是就决定移植到JSP里面。 

jsp文件名为 index.jsp,其实也可以使用过滤器来进行拦截,然后跳转到其他域名去。 

完整代码如下: 


<%@page import=”java.util.regex.Matcher”%> 

<%@page import=”java.util.regex.Pattern”%> 

<%@ page language=”java” pageEncoding=”UTF-8″%> 

<%! 

// b 是单词边界(连着的两个(字母字符 与 非字母字符) 之间的逻辑上的间隔), 
// 字符串在编译时会被转码一次,所以是 “\b” 
// B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔) 


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”; 

String tableReg = “\b(ipad|tablet|(Nexus 7)|up.browser” 

+”|[1-4][0-9]{2}x[1-4][0-9]{2})\b”; 

Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE); 

Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE); 

public boolean checkMobile(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; 





%> 

<% 

String path = request.getContextPath(); 

String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”; 

// 

String userAgent = request.getHeader( “USER-AGENT” ).toLowerCase(); 

if(null == userAgent){ 

userAgent = “”; 



if(checkMobile(userAgent)){ 

response.sendRedirect(basePath+”download.html”); 

//request.getRequestDispatcher(“/download.html”).forward(request,response); 

} else { 

response.sendRedirect(basePath+”index.html”); 

//request.getRequestDispatcher(“/index.html”).forward(request,response); 



%> 

转载请注明:代码学堂>编程开发 > jsp教程 > 如何使用jsp正则判断是否是移动设备

1. 本站所有资源来源于用户上传和网络,因此不包含技术服务请大家谅解!如有侵权请邮件联系客服!10210454@qq.com
2. 本站不保证所提供所有下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理,有奖励!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
4. 如果您也有好的资源或教程,您可以投稿发布,成功分享后有RB奖励和额外RMB收入!

磊宇堂正在使用的服务器 维护管理由磊宇云服务器提供支持

磊宇堂 » 如何使用jsp正则判断是否是移动设备

提供最优质的资源集合

立即查看 了解详情