获取用户信息

 1 /**
 2 * 获取用户名 从session中
 3 * 1.怎么拿到session? 不敢保证只有一个 装配不行 传参不行
 4 *
 5 * 通过RequestContextHolder 中的方法 可以获取的是当前请求
 6 */
 7 ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
 8 HttpServletRequest request = requestAttributes.getRequest();
 9 /**
10 * 通过当前请求 获取的一定是当前用户对应的session 参照session原理
11 */
12 HttpSession session = request.getSession();
13 // 从session中获取管理员信息
14 CmfzAdmin cmfzAdmin = (CmfzAdmin) session.getAttribute("admin");
15 cmfzLog.setUserName(cmfzAdmin.getUsername());
16 
17 // 获取ip地址
18 String ipAddrByRequest = IPKit.getIpAddrByRequest(request);
19 cmfzLog.setLogIp(ipAddrByRequest);

 


 

 1 public class IPKit {
 2 /**
 3 * @param request 请求
 4 * @return IP Address
 5 */
 6 public static String getIpAddrByRequest(HttpServletRequest request) {
 7 String ip = request.getHeader("x-forwarded-for");
 8 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
 9 ip = request.getHeader("Proxy-Client-IP");
10 }
11 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
12 ip = request.getHeader("WL-Proxy-Client-IP");
13 }
14 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
15 ip = request.getRemoteAddr();
16 }
19 return ip;
20 }
21 }

 

上一篇:获取ip地址


下一篇:ip