java如何获取用户登录ip、浏览器信息、SessionId
目录
- java获取用户登录ip、浏览器信息、SessionId
- 1、获取用户登录ip
- 2、获取用户所使用的浏览器信息
- 3、获取用户SessionId
- 获取用户登录的ip地址(考虑多种请求头的情况)
java获取用户登录ip、浏览器信息、SessionId
1、获取用户登录ip
//获取用户登录ip; String loginIp = request.getHeader("X-Forwarded-For"); if (loginIp == null || loginIp.length() == 0 || "unknown".equalsIgnoreCase(loginIp)) { loginIp = request.getHeader("X-Real-IP"); } if (loginIp == null || loginIp.length() == 0 || "unknown".equalsIgnoreCase(loginIp)) { loginIp = request.getHeader("Proxy-Client-IP"); } if (loginIp == null || loginIp.length() == 0 || "unknown".equalsIgnoreCase(loginIp)) { loginIp = request.getHeader("WL-Proxy-Client-IP"); } if (loginIp == null || loginIp.length() == 0 || "unknown".equalsIgnoreCase(loginIp)) { loginIp = request.getHeader("HTTP_CLIENT_IP"); } if (loginIp == null || loginIp.length() == 0 || "unknown".equalsIgnoreCase(loginIp)) { loginIp = request.getRemoteAddr(); }
2、获取用户所使用的浏览器信息
/** *获取浏览器信息; */ String ua = request.getHeader("User-Agent"); //转成UserAgent对象 UserAgent userAgent = UserAgent.parseUserAgentString(ua); Browser browser = userAgent.getBrowser(); String browserInfo=browser.toString();//浏览器名
3、获取用户SessionId
request.getSession().getId();
获取用户登录的ip地址(考虑多种请求头的情况)
这段代码网上找的,传一个HttpServletRequest request就行,直接用
public class IpUtil { /** * 获取登录用户IP地址 * * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if (ip.equals("0:0:0:0:0:0:0:1")) { ip = "本地"; } return ip; } }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)