1.11 用户登录_并把用户信息加密传到cookie中

一. 接口定义与实现

/**
 * 检索用户名和密码是否匹配,用于登录
 */
public Users queryUserForLogin(String username, String password);


@Transactional(propagation = Propagation.SUPPORTS)
@Override
public Users queryUserForLogin(String username, String password) {
    Example userExample = new Example(Users.class);
    Example.Criteria userCriteria = userExample.createCriteria();
    userCriteria.andEqualTo("username", username);
    userCriteria.andEqualTo("password", password);
    Users result = usersMapper.selectOneByExample(userExample);
    return result;
}

二.定义工具类CookieUtils和JsonUtils
请查看链接地址:http://www.gxcode.top/code
1.11 用户登录_并把用户信息加密传到cookie中_第1张图片

三.实现控制层方法

@ApiOperation(value = "用户登录", notes = "用户登录", httpMethod = "POST")
@PostMapping("/login")
public JSONResult login(@RequestBody UserBO userBO, HttpServletRequest request, HttpServletResponse response) throws Exception {
    String username = userBO.getUsername();
    String password = userBO.getPassword();
    // 0. 判断用户名和密码必须不为空
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
        return JSONResult.errorMsg("用户名或密码不能为空");
    }
    // 1. 实现登录
    Users userResult = userService.queryUserForLogin(username, MD5Utils.getMD5Str(password));
    if (userResult == null) {
        return JSONResult.errorMsg("用户名或密码不正确");
    }
    userResult = setNullProperty(userResult);
    CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(userResult), true);
    return JSONResult.ok(userResult);
}

private Users setNullProperty(Users userResult) {
    userResult.setPassword(null);
    userResult.setMobile(null);
    userResult.setEmail(null);
    userResult.setCreatedTime(null);
    userResult.setUpdatedTime(null);
    userResult.setBirthday(null);
    return userResult;
}

你可能感兴趣的:(java架构笔记,cookie加密,用户登录)