Java操作Cookie方法

特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/mao2080/

1、问题描述

  Cookie由服务端来写并将httpOnly设置成为“true”,Cookie中设置了"HttpOnly"属性,那么通过程序(JS脚本、Applet等)将无法读取到Cookie信息,这样能有效的防止XSS攻击。看图加深理解。

  

  

2、代码片段

1、设置cookie  

此处省略账号密码校验逻辑,省略用户信息存缓存步骤。

 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     }

2、获取cookie  

 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     }

3、参考网站

  https://blog.csdn.net/Truong/article/details/69063087

  https://www.cnblogs.com/lanxiamo/p/5889285.html

posted @ 2018-08-22 20:35  mao2080  阅读(22549)  评论(1编辑  收藏  举报