springboot 后台判断请求来自移动端访问还是PC端访问

103人浏览 / 0人评论

首先定义一个工具类,增加一个方法判断请求是否来自手机:

public class StringUtil {
    private final static String[] agent = { "Android", "iPhone", "iPod","iPad", "Windows Phone", "MQQBrowser" }; //定义移动端请求的所有可能类型
    /**
    * 判断User-Agent 是不是来自于手机
    * @param ua
    * @return
    */
    public static boolean checkAgentIsMobile(String ua) {
        boolean flag = false;
        if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
            // 排除 苹果桌面系统
            if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
                for (String item : agent) {
                    if (ua.contains(item)) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }
}

在SpringMVC框架controller类中增加一个如下方法:

@Controller
@RequestMapping("/test")
public class RedBagController {
    public ModelAndView testUa(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        String ua = request.getHeader("User-Agent");
        if(StringUtil.checkAgentIsMobile(ua)){
            map.put("mm", "来自移动端访问");
        }else{
            map.put("mm", "来自PC端访问");
        }
        return new ModelAndView("testUa","map",map);
    }
}

写一个前端页面并命名为 testUa.ftl, 代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport" id="viewport">
    <meta content="telephone=no" name="format-detection">
</head>
<body>
    ${map.mm}
</body>
</html>

全部评论