JSP determines the regex of a mobile device

  • 2020-09-16 07:45:03
  • OfStack

I saw a great article, "what do you do on the front end of Tmall?" , Tmall php to determine the mobile device regular (personal guess), found it very useful, so I decided to port to JSP.

The jsp file is called index.jsp, but you can also use filters to block it and then jump to another domain.

The complete code is as follows:
 
<%@page import="java.util.regex.Matcher"%> 
<%@page import="java.util.regex.Pattern"%> 
<%@ page language="java" pageEncoding="UTF-8"%> 
<%! 

// \b  It's the word boundary ( Two attached ( Alphabetic characters   with   Non-alphabetic character )  The logical interval between ), 
//  Strings are transcoded at compile time 1 time , So it is  "\\b" 
// \B  Is the logical interval within the word ( The logical interval between two consecutive alphabetic characters ) 
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 = ""; 
} 
//  matching  
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> Test the mobile device jump </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=" test , Mobile devices , jump "> 
<meta http-equiv="description" content=" Test the mobile device jump "> 
<!-- 
<link rel="stylesheet" type="text/css" href="styles.css"> 
--> 
</head> 

<body> 

<div id="pagecontent" style="min-height:500px;_height:500px;"> 

 Running! <br> 
</div> 

</body> 
</html> 

Related articles: