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);
}
//
%> <!DOCTYPE html>
<html lang="zh-cn">
<head>
<base rel="nofollow noopener noreferrer" href="<%=basePath%>"> <title>测试移动设备跳转</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="测试,移动设备,跳转">
<meta http-equiv="description" content="测试移动设备跳转">
<!--
<link rel="stylesheet" type="text/css" rel="nofollow noopener noreferrer" href="styles.css">
-->
</head> <body> <div id="pagecontent" style="min-height:500px;_height:500px;"> 正在运行!<br>
</div> </body>
</html>

到此这篇关于JSP判断移动设备的正则就介绍到这了。芷兰知香,怀情仰望天空,为青春呐喊;牡丹芬芳,抱爱脚踏实地,为年轻喝彩。更多相关JSP判断移动设备的正则内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

您可能有感兴趣的文章
JSP如何实现简单网页计算器

JSP动态如何实现web网页登陆和注册功能

JSP如何实现文件上传功能

SSM框架整合JSP中集成easyui前端ui项目开发示例详解

教你怎么用JSP统计网站访问人数