首页 > 移动平台 > 详细

JSP判断移动设备

时间:2014-03-06 17:08:53      阅读:633      评论:0      收藏:0      [点我收藏+]

日期: 2014年3月6日

人员::铁锚

看到了一篇很好的文章, 《在天猫,前端做什么?》,里面有天猫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 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" href="styles.css">
	-->
  </head>
  
  <body>
  
  <div id="pagecontent" style="min-height:500px;_height:500px;">
  
    正在运行!<br>
  </div>
    
  </body>
</html>


JSP判断移动设备,布布扣,bubuko.com

JSP判断移动设备

原文:http://blog.csdn.net/renfufei/article/details/20615723

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!