在下面的内容中,我将介绍基于SpringMVC的一些Cookie常用操作,包括:cookie的增、删、改、查
一 Cookie的属性简介
对于一个Cookie来说,一般有以下几个属性:
wKioL1g7jNqAPi17AABx-VgU5Gg747.png-
Name:一个cookie的名字
-
Value:一个cookie的值
-
Domain:可以访问该cookie的域名。非顶级域名,如二级域名或者三级域名,设置的cookie的domain只能为顶级域名或者二级域名或者三级域名本身,不能设置其他二级域名的cookie,否则cookie无法生成;顶级域名只能设置domain为顶级域名,不能设置为二级域名或者三级域名,否则cookie无法生成;二级域名能读取设置了domain为顶级域名或者自身的cookie,不能读取其他二级域名domain的cookie。所以要想cookie在多个二级域名中共享,需要设置domain为顶级域名,这样就可以在所有二级域名里面或者到这个cookie的值了;顶级域名只能获取到domain设置为顶级域名的cookie,其他domain设置为二级域名的无法获取
-
Path:可以访问此cookie的页面路径
-
Expires/Max-Age:该cookie的超时时间。若设置为一个具体的时间,那么当到达此时间后,此cookie失效;不设置的话默认值是Session,当前会话结束后该cookie失效(PS:比如关闭浏览器)
-
Size:该cookie的大小
-
HTTP:cookie的httponly属性。若此属性为true,那么在客户端则不能通过脚本(PS:比如JavaScript)来读取该cookie值
-
Secure:若此属性为true,cookie 只能在 HTTPS 连接中被浏览器传递到服务器端进行会话验证,如果是 HTTP 连接则不会传递该cookie
注:该视图可以在浏览器中按F12,在Resources栏目中看到
二 关于Cookie的一个简单入门示例
(1)在一个Controller中手动设置cookie的一些参数:
@RequestMapping("/hello.html")
public ModelAndView hello(@CookieValue(name="hitCounter",defaultValue="0")Long hitCounter,HttpServletResponse response){
ModelAndView mAndView = new ModelAndView("hello");
hitCounter++;
Cookie hit = new Cookie("hitCounter", hitCounter.toString());
hit.setHttpOnly(true); //如果设置了"HttpOnly"属性,那么通过程序(JS脚本、Applet等)将无法访问该Cookie
hit.setMaxAge(60 * 60); //设置生存期为1小时
// hit.setDomain("www.zifansky.cn"); //子域,在这个子域下才可以访问该Cookie
// hit.setPath("/hello"); //在这个路径下面的页面才可以访问该Cookie
// hit.setSecure(true); //如果设置了Secure,则只有当使用https协议连接时cookie才可以被页面访问
response.addCookie(hit);
return mAndView;
}
在这里,通过手动创建了一个cookie,并设置了一系列的参数,最后通过HttpServletResponse传递到返回页中
(2)hello.jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>SpringMVC Cookie Demo</title>
</head>
<body>
<div align="center">
<h2>SpringMVC Cookie Demo</h2>
Page hit counter: <b> ${cookie.hitCounter.value} </b>
</div>
</body>
</html>
最后的显示效果如下:
wKiom1g7jRyj6LplAACLJuB9hUg651.png然后每次刷新页面,页面中的数字都会增加
三 Cookie的增删改查示例
(1)新建一个CookieUtils类,用于写cookie的基本增删改查:
package cn.zifangsky.utils;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
public class CookieUtils {
/**
* 添加一个新Cookie
*
* @author zifangsky
* @param response
* HttpServletResponse
* @param cookie
* 新cookie
*
* @return null
*/
public static void addCookie(HttpServletResponse response, Cookie cookie) {
if (cookie != null)
response.addCookie(cookie);
}
/**
* 添加一个新Cookie
*
* @author zifangsky
* @param response
* HttpServletResponse
* @param cookieName
* cookie名称
* @param cookieValue
* cookie值
* @param domain
* cookie所属的子域
* @param httpOnly
* 是否将cookie设置成HttpOnly
* @param maxAge
* 设置cookie的最大生存期
* @param path
* 设置cookie路径
* @param secure
* 是否只允许HTTPS访问
*
* @return null
*/
public static void addCookie(HttpServletResponse response, String cookieName, String cookieValue, String domain,
boolean httpOnly, int maxAge, String path, boolean secure) {
if (cookieName != null && !cookieName.equals("")) {
if (cookieValue == null)
cookieValue = "";
Cookie newCookie = new Cookie(cookieName, cookieValue);
if (domain != null)
newCookie.setDomain(domain);
newCookie.setHttpOnly(httpOnly);
if (maxAge > 0)
newCookie.setMaxAge(maxAge);
if (path == null)
newCookie.setPath("/");
else
newCookie.setPath(path);
newCookie.setSecure(secure);
addCookie(response, newCookie);
}
}
/**
* 添加一个新Cookie
*
* @author zifangsky
* @param response
* HttpServletResponse
* @param cookieName
* cookie名称
* @param cookieValue
* cookie值
* @param domain
* cookie所属的子域
*
* @return null
*/
public static void addCookie(HttpServletResponse response, String cookieName, String cookieValue, String domain) {
addCookie(response, cookieName, cookieValue, domain, true, CookieConstantTable.COOKIE_MAX_AGE, "/", false);
}
/**
* 根据Cookie名获取对应的Cookie
*
* @author zifangsky
* @param request
* HttpServletRequest
* @param cookieName
* cookie名称
*
* @return 对应cookie,如果不存在则返回null
*/
public static Cookie getCookie(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
if (cookies == null || cookieName == null || cookieName.equals(""))
return null;
for (Cookie c : cookies) {
if (c.getName().equals(cookieName))
return (Cookie) c;
}
return null;
}
/**
* 根据Cookie名获取对应的Cookie值
*
* @author zifangsky
* @param request
* HttpServletRequest
* @param cookieName
* cookie名称
*
* @return 对应cookie值,如果不存在则返回null
*/
public static String getCookieValue(HttpServletRequest request, String cookieName) {
Cookie cookie = getCookie(request, cookieName);
if (cookie == null)
return null;
else
return cookie.getValue();
}
/**
* 删除指定Cookie
*
* @author zifangsky
* @param response
* HttpServletResponse
* @param cookie
* 待删除cookie
*/
public static void delCookie(HttpServletResponse response, Cookie cookie) {
if (cookie != null) {
cookie.setPath("/");
cookie.setMaxAge(0);
cookie.setValue(null);
response.addCookie(cookie);
}
}
/**
* 根据cookie名删除指定的cookie
*
* @author zifangsky
* @param request
* HttpServletRequest
* @param response
* HttpServletResponse
* @param cookieName
* 待删除cookie名
*/
public static void delCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
Cookie c = getCookie(request, cookieName);
if (c != null && c.getName().equals(cookieName)) {
delCookie(response, c);
}
}
/**
* 根据cookie名修改指定的cookie
*
* @author zifangsky
* @param request
* HttpServletRequest
* @param response
* HttpServletResponse
* @param cookieName
* cookie名
* @param cookieValue
* 修改之后的cookie值
* @param domain
* 修改之后的domain值
*/
public static void editCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,String domain) {
Cookie c = getCookie(request, cookieName);
if (c != null && cookieName != null && !cookieName.equals("") && c.getName().equals(cookieName)) {
addCookie(response, cookieName, cookieValue, domain);
}
}
}
注:上面用到的CookieConstantTable类,其内容如下:
package cn.zifangsky.utils;
public class CookieConstantTable {
// cookie的有效期默认为30天
public final static int COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
//cookie加密时的额外的salt
public final static String salt = "www.zifangsky.cn";
//自动登录的Cookie名
public final static String RememberMe = "remember-me";
}
(2)在上面的controller中新添加几个方法:
@RequestMapping("/testAddCookie.html")
public ModelAndView addCookie(HttpServletResponse response){
ModelAndView mAndView = new ModelAndView("show");
// CookieUtils.addCookie(response, "test_addCookie", UUID.randomUUID().toString(), null);
CookieUtils.addCookie(response, "test_2", UUID.randomUUID().toString() + new Random(1000).nextInt(), "localhost");
return mAndView;
}
@RequestMapping("/testGetCookie.html")
public void getCookie(HttpServletRequest request){
System.out.println(CookieUtils.getCookieValue(request, "test_2"));
}
@RequestMapping("/testEditCookie.html")
public ModelAndView editCookie(HttpServletRequest request,HttpServletResponse response){
ModelAndView mAndView = new ModelAndView("show");
CookieUtils.editCookie(request, response, "test_2", "editeditedit", "localhost");
return mAndView;
}
@RequestMapping("/testDelCookie.html")
public void delCookie(HttpServletRequest request,HttpServletResponse response){
CookieUtils.delCookie(request, response, "test_2");
}
}
(3)显示cookie的show.jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<title>SpringMVC Cookie Demo</title>
</head>
<body>
<div align="center">
<h2>SpringMVC Cookie Demo</h2>
The Cookie is: <b> ${cookie.test_2.value} </b>
</div>
</body>
</html>
(4)效果测试:
i)新建cookie:
访问:http://localhost:9180/CookieDemo/testAddCookie.html
wKioL1g7jX_Qde8qAACmlK65Yuc424.pngii)获取cookie:
访问:http://localhost:9180/CookieDemo/testGetCookie.html
输出如下:
14583736-4f5e-4411-9785-f19e9190a0b4-1244746321
iii)修改cookie:
访问:http://localhost:9180/CookieDemo/testEditCookie.html
wKioL1g7jarCRuwPAACbv4y_xY0233.pngiv)删除cookie:
访问:http://localhost:9180/CookieDemo/testDelCookie.html
wKiom1g7jcyBK37sAABzYgxyoyg470.png
网友评论