Java 获取系统当前登录用户信息

1,代码,并调用方法


// HttpServletRequest request 接收请求数据
    @RequestMapping("/tosave")
    @ResponseBody
    public Map tosave(@RequestParam HashMap<String,String> paraMap, Model model, HttpServletRequest request, HttpServletResponse response) {
        try {
            Date date = new Date();//获取当前的日期
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            if (!StringUtil.isNullOrSpace(paraMap.get("id"))) {
               
                Tbz4BaseEntity entity=new Tbz4BaseEntity();
//                BeanUtils.copyProperties(tbz4DbzreportLogEntity,entity);
                entity.setId(UUID.randomUUID().toString());
                entity.setUserid(RightUtil.getCurrentUser(request).getUid());  // 获取当前用户id
                entity.setUsername(RightUtil.getCurrentUser(request).getUname()); // 获取当前用户名
                entity.setCreated(df.format(date));
                tbz4BaseEntityDao.save(entity);

            }
            HashMap<String, Object> result = createResult(true, "操作成功!");
            return result;
        } catch (Exception e) {
            log.error("系统错误!" + e.getMessage(), e);
            return createResult(Boolean.FALSE, "操作失败。");
        }
    }

2,方法

public class RightUtil {

    public RightUtil() {
    }

    public static SessionUserInfoEntity getCurrentUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        SessionUserInfoEntity sessionUserInfoEntity = (SessionUserInfoEntity)session.getAttribute(Public.SESSION_USER_KEY);
        if (sessionUserInfoEntity != null) {
            return sessionUserInfoEntity;
        } else {
            String sessionUserInfoEntityJson = request.getHeader(Public.SESSION_USER_KEY);
            sessionUserInfoEntityJson = sessionUserInfoEntityJson == null ? request.getParameter(Public.SESSION_USER_KEY) : sessionUserInfoEntityJson;
            if (!StringUtil.isEmptyOrLength0(sessionUserInfoEntityJson)) {
                return SessionUserInfoEntity.fromCookieJson(sessionUserInfoEntityJson);
            } else {
                Cookie[] cookies = request.getCookies();
                cookies = cookies == null ? new Cookie[0] : cookies;
                Cookie[] var5 = cookies;
                int var6 = cookies.length;

                for(int var7 = 0; var7 < var6; ++var7) {
                    Cookie cookie = var5[var7];
                    if (Public.SESSION_USER_KEY.equals(cookie.getName())) {
                        return SessionUserInfoEntity.fromCookieJson(cookie.getValue());
                    }
                }

                sessionUserInfoEntity = new SessionUserInfoEntity();
                sessionUserInfoEntity.setUid("");
                sessionUserInfoEntity.setLname("");
                return sessionUserInfoEntity;
            }
        }
    }
}

你可能感兴趣的:(Java)