发表于: 2020-08-27 22:42:58
1 1360
/**
* 自定义拦截器
*/
public class MyInterceptor1 implements HandlerInterceptor {
@Autowired
AccountService accountService;
//日志
private static Logger logger =LogManager.getLogger(MyInterceptor1.class);
//进入 Handler方法之前执行
//应用场景:用于身份认证(登录认证)、身份授权(权限校验)
//此方法返回false表示拦截,不向下执行,返回true表示放行
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 判断cookie中是否携带token,并进行验证
Cookie[] cookies = request.getCookies();
if (cookies != null) {
logger.info("Cookie长度为: " + cookies.length);
logger.info("拦截器获取到的Cookie: " + String.valueOf(cookies));
logger.info("开始遍历");
// 遍历
for (Cookie cookie : cookies) {
logger.info("当前cookie的值: " + cookie.getValue() + " 名字为:" + cookie.getName());
// 判断是否有token
if (cookie.getName().equals("token")) {
String tokenDES = cookie.getValue();
logger.info("tokenDES: " + tokenDES);
String token = DESUtils.getDecryptString(tokenDES);//解密
logger.info("token的解密value:" + token);
// 分割字符串 获取id
Long id = Long.valueOf(token.split("=")[0]);
logger.info("id为: " + id);
//验证token有效性
if (accountService.select(new Account(id)) != null) {
return true;
} else {
logger.debug("token验证失败,跳回登陆页面");
// httpServletRequest https://blog.csdn.net/gris0509/article/details/6340987
response.sendRedirect(request.getContextPath() + "/login");
return false;
}
}
}
}
logger.debug("cookies不存在");
response.sendRedirect(request.getContextPath() + "/login");
return false;
}
登录有点问题
//登录
@RequestMapping(value = "login")
public String login(Account account, Model model, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
logger.info("加密前的信息:" + account);
if (account.getUsername() != null && account.getPassword() != null) {
//将密码通过MD5进行加密
String passwordMD5 = MD5Util.stringToMD5(account.getPassword());
account.setPassword(passwordMD5);
logger.info("加密后的信息:" + account);
Account account1 = accountService.select(account);
//验证账号密码是否正确
if (account1 != null) {
logger.info("登录成功");
Long id = account1.getId();//根据用户名获取id
//使用系统当前时间生成唯一token,格式为键值对
String token = id + "=" + System.currentTimeMillis();
//使用DES加密
String tokenDES = DESUtils.getEncryptString(token);
logger.info("加密后的token:" + tokenDES);
//保存到cookies中
Cookie cookie = new Cookie("token", tokenDES);
//设置cookie过期时间 单位为秒
cookie.setMaxAge(3600);
//设置cookie有效路径
cookie.setPath("/");
httpServletResponse.addCookie(cookie);
return "redirect:/a/profession";
} else {
model.addAttribute("error", "账号或密码错误");//如果账号密码错误则提示该消息
return "login";
}
} else {
model.addAttribute("error", "请先登录");//如果未登录就访问/u/profession则提示该消息
return "login";
}
Account account1 = accountService.select(account);
这里没看懂
今日问题暂无
评论