原文地址: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; } } } }