java判断访问方式是手机端还是电脑端的工具类

阳光穿透心脏的1/2处 2024-02-18 18:31 89阅读 0赞

检查访问方式是手机端还是电脑端的工具类

  1. 对request请求头,user-agent的值进行正则判断

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    /**

    • 检测是否为移动端设备访问
    • @author Administrator
      /
      public class CheckMobile {
  1. //手机
  2. static String phoneReg="\\b(ip(hone|od)|android|opera m(ob|in)i"
  3. +"|windows (phone|ce)|blackberry"
  4. +"|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
  5. +"|laystation portable)|nokia|fennec|htc[-_]"
  6. +"|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
  7. //平板
  8. static String tableReg="\\b(ipad|tablet|(Nexus 7)|up.browser"
  9. +"|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
  10. //移动设备正则表达式匹配:手机端、平板
  11. static Pattern phonePat =Pattern.compile(phoneReg,Pattern.CASE_INSENSITIVE);
  12. static Pattern tablePat =Pattern.compile(tableReg,Pattern.CASE_INSENSITIVE);
  13. public static boolean check(String userAgent){
  14. if(null==userAgent){
  15. userAgent="";
  16. }
  17. //开始匹配
  18. Matcher matcherPhone=phonePat.matcher(userAgent);
  19. Matcher matcherTable=tablePat.matcher(userAgent);
  20. if(matcherPhone.find()||matcherTable.find()){
  21. //移动设备入口
  22. return true;
  23. }else{
  24. //pc端入口
  25. return false;
  26. }
  27. }
  28. }

2.调用

  1. /**
  2. * 检查访问方式
  3. */
  4. public void checkEquipment(HttpServletRequest request,HttpServletResponse response){
  5. String ua=(String) session.getAttribute(request,"ua");
  6. if(null==ua){
  7. try{
  8. String userAgent = request.getHeader( "USER-AGENT" ).toLowerCase();
  9. if(null == userAgent){
  10. userAgent = "";
  11. }
  12. if(CheckMobile.check(userAgent)){
  13. ua="mobile";
  14. } else {
  15. ua="pc";
  16. }
  17. session.setAttribute(request, response, "ua",ua);
  18. }catch(Exception e){}
  19. }
  20. if(StringUtils.isNotBlank((ua) )){
  21. request.setAttribute("ua", ua);
  22. }
  23. }

发表评论

表情:
评论列表 (有 0 条评论,89人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PHP判断电脑手机访问

    最近的项目中使用到了电脑和手机2个不同平台的相互切换,一开始想使用JS判断,后来一想直接在项目入口出判断即可,并且方便: 代码直接可以使用,可以直接测试: <?ph

    相关 判断手机PC代码

    那天做到一个需要判断是手机端还是PC端的功能。我也不太懂,自己不会写,就在网上找了一下。 找到的答案也是有的五花八门,最后看到一个比较简洁的就试用了一下,没得问题就继续用着了