为测试方便,代码为测试代码,可根据需要进行修改
// 将Cookie放入浏览器
@ResponseBody
@RequestMapping(value = "/putCookies", method = RequestMethod.POST)
public ResultJson putCookies(HttpServletResponse response,
HttpServletRequest request) {
ResultJson rj = new ResultJson();
// new一个Cookie对象,键值对为参数name--->value
Cookie cookie = new Cookie("demo", "demo");
// tomcat下多应用共享
cookie.setPath("/");
// 如果cookie的值中含有中文时,需要对cookie进行编码,不然会产生乱码
try {
URLEncoder.encode("demo", "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
cookie.setMaxAge(10000);//设置有效时间
// 将Cookie添加到Response中,使之生效
response.addCookie(cookie); // addCookie后,如果已经存在相同名字的cookie,则最新的覆盖旧的cookie
rj.setData("----");
return rj;
}
// 从浏览器中取出Cookie
@ResponseBody
@RequestMapping(value = "/getCookies", method = RequestMethod.POST)
public ResultJson getCookies(HttpServletResponse response,
HttpServletRequest request) {
ResultJson rj = new ResultJson();
// 从cookie中取出token
Cookie[] cookies = request.getCookies();// 这样便可以获取一个cookie数组
Map<String, Object> cookieMap = new HashMap<String, Object>();
for (Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie.getValue());
}
rj.setData(cookieMap);
return rj;
}
测试结果:
demo—>demo即为刚放入的cookie