Cookie由服务端来写并将httpOnly设置成为“true”,Cookie中设置了"HttpOnly"属性,那么经过程序(JS脚本、Applet等)将没法读取到Cookie信息,这样能有效的防止XSS攻击。看图加深理解。html
此处省略帐号密码校验逻辑,省略用户信息存缓存步骤。缓存
1 @RequestMapping("/login") 2 @ResponseBody 3 public void login(HttpServletRequest request, HttpServletResponse response) throws IOException { 4 Cookie cookie = new Cookie("access_token", UUID.randomUUID().toString()); 5 cookie.setHttpOnly(true); 6 cookie.setPath("/"); 7 cookie.setDomain("localhost"); 8 response.addCookie(cookie); 9 response.sendRedirect("http://localhost:8088/index.html"); 10 }
1 /** 2 * 获取cookie 3 * @param request 4 * @param key 5 * @return 6 */ 7 public static String getCookie(HttpServletRequest request, String key){ 8 if(request == null || StringUtil.isEmpty(key)){ 9 return ""; 10 } 11 Cookie[] cookies = request.getCookies(); 12 for (Cookie cookie : cookies) { 13 if(key.equals(cookie.getName())){ 14 return cookie.getValue(); 15 } 16 } 17 return ""; 18 }