javaweb判断当前请求是否为移动设备访问的方法

由于移动端和pc端还是稍微有些区别的,我觉得最好是在一个地儿统一判断,而且不要改动原先的代码,这样可以从一定程度上减少bug的数量。我的想法是首先应该判断当前请求是否为移动端,然后设一个标识到session中,然后就可以随便处理了。不管你是单独处理,还是统一处理,直接读取session就可以做相应的判断了。

我封装成了一个类,现在分享给大家:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package
com.tgb.util;
  
import
java.util.regex.Matcher;
import
java.util.regex.Pattern;
  
/**
 
* 检测是否为移动端设备访问
 
*
 
* @author  :
 
* @group  :
 
* @Version  :
 
* @Date  :
 
*/
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 = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
 
static
Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);
   
 
/**
  
* 检测是否是移动设备访问
  
*
  
* @Title: check
  
* @Date :
  
* @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
;
  
}
 
}
}

 使用方式:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 
* 检查访问方式是否为移动端
 
*
 
* @Title: check
 
* @Date :
 
* @param request
 
* @throws IOException
 
*/
public
boolean
check(HttpServletRequest request,HttpServletResponse response)
throws
IOException{
 
boolean
isFromMobile=
false
;
   
 
HttpSession session= request.getSession();
 
//检查是否已经记录访问方式(移动端或pc端)
 
if
(
null
==session.getAttribute(
"ua"
)){
  
try
{
   
//获取ua,用来判断是否为移动端访问
   
String userAgent = request.getHeader(
"USER-AGENT"
).toLowerCase();
   
if
(
null
== userAgent){
    
userAgent =
""
;
   
}
   
isFromMobile=CheckMobile.check(userAgent);
   
//判断是否为移动端访问
   
if
(isFromMobile){
    
System.out.println(
"移动端访问"
);
    
session.setAttribute(
"ua"
,
"mobile"
);
   
}
else
{
    
System.out.println(
"pc端访问"
);
    
session.setAttribute(
"ua"
,
"pc"
);
   
}
  
}
catch
(Exception e){}
 
}
else
{
  
isFromMobile=session.getAttribute(
"ua"
).equals(
"mobile"
);
 
}
   
 
return
isFromMobile;
}

在登录的时候,或者在action的execute中调用这个方法,不用改动原先的业务逻辑,即可判断请求的是否为移动端,然后再根据结果去做相应处理,应该就简单多了。