Cookie的使用
浏览器保存Cookie的值:response
服务端从request获取Cookie的值
@Controller("user_
controller")
@RequestMapping("/user")
public
class UserController{
@Autowired
@Qualifier("user
Service") /* 一个
接口多个实现用name区分*/
private IUserService userService;
@RequestMapping("/")
public String list(Model model,Http
ServletResponse response) {
//1、保存cookie的值
String token = UUID.randomUUID().toString();
Cookie cookie=new Cookie("token",token);
cookie.setMaxAge(60*60*24);
cookie.setPath("/");
response.addCookie(cookie);
System.out.println("token: "+token);
List<UserPO> list = null;
model.addAttribute("userList", list);
return "user/index";
}
private String getCookieToken(HttpServletRequest request){
Cookie[]cookies= request.getCookies();
for(Cookie c:cookies){
if(c.getName().equals("token")){
return c.getValue();
}
}
return null;
}
private void addCookie(HttpServletResponse response,String token){
//redisService.set("user","token",user);
Cookie cookie=new Cookie("token",token);
cookie.setPath("/");
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
}
@RequestMapping("/{id}")
public String get(@PathVariable String id, Model model,
HttpServletRequest request, HttpServletResponse response){
//2、获取cookie的值
String cookieToken=getCookieToken(request);
System.out.println("token: "+cookieToken);
if(cookieToken==null){
return null;
}else{
// Users user=redisService.get(UserKeyPrefix.user, token, Users.class);
/*
* 还需要将cookie重新发给浏览器,重新设置token到redis
* 以便于刷新过期时间
*/
addCookie(response,cookieToken);
}
UserVO user = new UserVO();
model.addAttribute("user", user);
//"forward:index";
//return "redirect:index";
return "index";
}
}