发表于: 2017-10-31 22:32:04
1 702
今天完成的事
重构代码
让项目看起来更简洁,去掉不必要的语句
注册过程
// 注册过程
@RequestMapping(value = "/userR", method = RequestMethod.POST)
public String userR(HttpServletRequest request, HttpServletResponse response) {
User user = new User();
user.setName(request.getParameter("name"));
user.setPassword(request.getParameter("password"));
user.setStudytype(request.getParameter("studytype"));
if (user.getName().length() > 1 && user.getPassword().length() > 1) {
UUID uu = UUID.randomUUID();
user.setId(uu.toString().replace("-", ""));
user.setStates("学习中");
user.setPassword(AppMD5Util.getMD5(user.getPassword()));
user.setCreatetime((new Date().getTime()));
user.setLogintime((new Date().getTime()));
userService.add(user);
desUtil.setKey(key);
desUtil.setEncString(user.getId() + "," + user.getLogintime());
Cookie cookie = new Cookie("token", desUtil.getStrMi());
cookie.setPath("/");
cookie.setMaxAge(5 * 60);
response.addCookie(cookie);
return "redirect:/home";
}
return "/error1";
}
对象user从request中拿取前台表单中传过来的值
这里对注册的账号和密码可以做了一些要求,比如必须要有两个字符,长度要大于等于2
为了保险起见,建议加一条判定username不和数据库中已有name重合的规则
创建和登录时间都取当前时间
设置密钥对token的值加密,加密对象为id和logintime
为什么不对帐号和密码加密呢
因为帐号和密码都是很敏感的数据,而cookie的安全性没有想象中来的那么好
在响应过程中给浏览器添加一个cookie,此处有效时间为5分钟,即使关闭浏览器,再次打开首页,依然会判定有效
登录过程
// 登录过程
@RequestMapping(value="/userL",method = RequestMethod.POST)
public String userL(HttpServletRequest request,HttpServletResponse response){
User user = new User();
user.setName(request.getParameter("name"));
user.setPassword(AppMD5Util.getMD5(request.getParameter("password")));
User temp = userService.findByUser(user);
if (temp!=null){
request.getSession().setAttribute("time",new Date().getTime());
request.getSession().setAttribute("loginuser",temp);
temp.setLogintime(new Date().getTime());
desUtil.setKey(key);
desUtil.setEncString(temp.getId()+""+temp.getLogintime());
Cookie cookie = new Cookie("token",desUtil.getStrMi());
cookie.setPath("/");
cookie.setMaxAge(5*60);
response.addCookie(cookie);
return "/redirect:/home";
}
return "/error2";
}
同样从request中获取name和password的值
通过这两个参数匹配数据库中的对象数据
当匹配到以后
请求会在session中添加属性loginuser和time
登陆账号的login需要重新刷新为当前时间并重新制作令牌
登录后重定向到home
退出过程
@RequestMapping("/exit")
public String exit(HttpServletRequest request,HttpServletResponse response){
request.getSession().removeAttribute("loginUser");
request.getSession().removeAttribute("time");
Cookie cookie = new Cookie("token",null);
cookie.setPath("/");
cookie.setMaxAge(0);
response.addCookie(cookie);
return "redirect:/home";
}
移除session属性loginUser以改变前台header状态
把cookie的值设为空,这样下次进首页就不会自动登录了
MaxAge设为0同样可以消除令牌,这里对自动登录的可能性做了两次否定
遇到的问题
.png)

在服务器上的拦截器取不到我token的第二个值
拦截器在本地运行没有任何问题
但是在服务器上就不行
为此我才对代码进行一次梳理,以求逻辑更清晰
.png)

我这样写假如没登陆就进首页会不会是个死循环啊?
不停地重定向到home
明天计划的事
对任务5的收尾和任务6的开始
收获
对转发和重定向有了一些了解
转发就是一个请求,一个响应
重定向是两个请求,两个响应
客户端向服务端发送一个请求,服务端响应并且要求客户端再发送一个请求,客户端发送请求,服务端再响应
评论