java和javaScript设置cookie的有效期不同,java是设置有效时间的秒数,而javaScript设置的是有效日期的字符串。
设置cookie时要注意cookie的路径问题,在页面读取cookie时,只能够读取到页面本级目录的cookie和上级目录的cookie,其他都不会读取到。
java 读写删cookie
/**
* 获取cookie值
*
* @param cookieName
* @param request
* @param response
* @return
*/
public static String getCookieValue(String cookieName) {
if (cookieName == null || cookieName.equals("")) {
return "";
}
HttpServletRequest request = ServletActionContext.getRequest();
Cookie[] cookies = request.getCookies();
int length = 0;
if (cookies != null && cookies.length > 0) {
length = cookies.length;
for (int i = 0; i < length; i++) {
String cname = cookies[i].getName();
if (cname != null && cname.equals(cookieName)) {
String cValue = cookies[i].getValue();
return cValue;
} else {
continue;
}
}
return "";
} else {
return "";
}
}
/**
* 写入cookie 值
*
* @param cookieName
* cookie名称
* @param value
* cookie值
* @param expireHours
* cookie有效小时数
* @return
*/
public static void setCookie(String cookieName, String value,
int expireHours) {
HttpServletResponse response = ServletActionContext.getResponse();
Cookie cookie = new Cookie(cookieName, value);
cookie.setPath("/");// 这个要设置
cookie.setDomain(".bessystem.com");// 这样设置,能实现两个网站共用
if (expireHours != 0) {
expireHours = expireHours * 60 * 60; // 不设置的话,则cookies不写入硬盘,而是写在内存,只在当前页面有用,以秒为单位
}
cookie.setMaxAge(expireHours);
response.addCookie(cookie);
}
/**
* 删除cookie
*
* @param cookieName
*/
public static void deleteCookie(String cookieName) {
if (cookieName == null || cookieName.equals("")) {
return ;
}
HttpServletRequest request = ServletActionContext.getRequest();
Cookie[] cookies = request.getCookies();
int length = 0;
if (cookies != null && cookies.length > 0) {
length = cookies.length;
for (int i = 0; i < length; i++) {
String cname = cookies[i].getName();
if (cname != null && cname.equals(cookieName)) {
String cValue = cookies[i].getValue();
setCookie(cname,cValue,0);
} else {
continue;
}
}
}
}
javascript 读取cookie值
function getCookieVal(cookieName)
{
var search = cookieName + "="
var returnvalue = "";
if (document.cookie.length > 0)
{
offset = document.cookie.indexOf(search);
if (offset != -1)
{
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1)
end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
javascript写入cookie
function setCookie( name, value, expires, path, domain, secure ) {
var today = new Date();
today.setTime( today.getTime() );
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}