Java实现对cookie的增删改查

2018-06-18 03:03:45来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

原文地址:http://blog.csdn.net/k21325/article/details/54377830   
@RequestMapping(value="meeting/addGuanzhu.do",method=RequestMethod.POST) @ResponseBody public Map<String, Object> addGuanzhu(HttpServletRequest request,HttpServletResponse response, Model model, String submitter) throws UnsupportedEncodingException { Map<String, Object> reMap = new HashMap<String, Object>(); //获取登录用户id String adminId = tsAdminService.getAdminIdCookie(request); System.out.println(submitter); if(submitter!=null && !"".equals(submitter)){ if(submitter!=null&&!"".equals(submitter)){ Cookie cookie = new Cookie(adminId.trim(), URLEncoder.encode(submitter.trim(), "UTF-8")); cookie.setMaxAge(60 * 60 * 24 * 360);// 设置为30min cookie.setPath("/"); response.addCookie(cookie); reMap.put("success", "success"); }else{ reMap.put("success", "false"); } }else{ CookieUtils.delCookieByName(request, response, adminId); reMap.put("success", "false"); } return reMap; } CookieUtils工具类 // 根据名称获取cookie public static Cookie getCookieByName(HttpServletRequest request, String name) { Map<String, Cookie> cookieMap = ReadCookieMap(request); if (cookieMap.containsKey(name)) { Cookie cookie = (Cookie) cookieMap.get(name); return cookie; } else { return null; } } // 先把cookie封装到Map中 private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) { Map<String, Cookie> cookieMap = new HashMap<String, Cookie>(); Cookie[] cookies = request.getCookies(); if (null != cookies) { for (Cookie cookie : cookies) { cookieMap.put(cookie.getName(), cookie); } } return cookieMap; } // 根据名称删除cookie public static void delCookieByName(HttpServletRequest request, HttpServletResponse response, String name) { Cookie[] cookies = request.getCookies(); if (null == cookies) { System.out.println("没有cookie=============="); } else { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { cookie.setValue(null); cookie.setMaxAge(0);// 立即销毁cookie cookie.setPath("/"); System.out.println("被删除的cookie名字为:" + cookie.getName()); response.addCookie(cookie); break; } } } } //根据名称修改cookie的值 public void editCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) { Cookie[] cookies = request.getCookies(); if (null == cookies) { System.out.println("没有cookie=============="); } else { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { System.out.println("原值为:" + cookie.getValue()); cookie.setValue(value); cookie.setPath("/"); cookie.setMaxAge(30 * 60);// 设置为30min System.out.println("被修改的cookie名字为:" + cookie.getName() + ",新值为:" + cookie.getValue()); response.addCookie(cookie); break; } } } }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Date与String之间的转换

下一篇:Tomcat异常:The Tomcat server configuration at\Servers\Tomca