Java中删除cookie
Cookie[] cookies=request.getCookies();
//cookies不为空,则清除
if(cookies!=null)
{
String value=cookies[0].getName();
//查找用户名
if(value.equals("userName"))
{
cookies[0].setMaxAge(0);
response.addCookie(cookies[i]);
}
}
//cookies不为空,则清除
if(cookies!=null)
{
String value=cookies[0].getName();
//查找用户名
if(value.equals("userName"))
{
cookies[0].setMaxAge(0);
response.addCookie(cookies[i]);
}
}
Java中如何读写cookie
//写cookie
Cookie namecookie = new Cookie("name",name);
Cookie passwordcookie = new Cookie("password",password);
Cookie optioncookie = new Cookie("option","1");
//生命周期
namecookie.setMaxAge(60*60*24*365);
passwordcookie.setMaxAge(60*60*24*365);
optioncookie.setMaxAge(60*60*24*365);
response.addCookie(namecookie);
response.addCookie(passwordcookie);
response.addCookie(optioncookie);
//读cookie
Cookie[] cookies = request.getCookies();
if(cookies!=null)
{
String name = "";
String password = "";
String option = "";
for (int i = 0; i < cookies.length; i++)
{
Cookie c = cookies[i];
if(c.getName().equalsIgnoreCase("name"))
{
name = c.getValue();
}
else if(c.getName().equalsIgnoreCase("password"))
{
password = c.getValue();
}
else if(c.getName().equalsIgnoreCase("option"))
{
option = c.getValue();
}
}
}
Cookie namecookie = new Cookie("name",name);
Cookie passwordcookie = new Cookie("password",password);
Cookie optioncookie = new Cookie("option","1");
//生命周期
namecookie.setMaxAge(60*60*24*365);
passwordcookie.setMaxAge(60*60*24*365);
optioncookie.setMaxAge(60*60*24*365);
response.addCookie(namecookie);
response.addCookie(passwordcookie);
response.addCookie(optioncookie);
//读cookie
Cookie[] cookies = request.getCookies();
if(cookies!=null)
{
String name = "";
String password = "";
String option = "";
for (int i = 0; i < cookies.length; i++)
{
Cookie c = cookies[i];
if(c.getName().equalsIgnoreCase("name"))
{
name = c.getValue();
}
else if(c.getName().equalsIgnoreCase("password"))
{
password = c.getValue();
}
else if(c.getName().equalsIgnoreCase("option"))
{
option = c.getValue();
}
}
}
setMaxAge(参数):参数为负数代表关闭浏览器时清除cookie,参数为0时代表删除cookie,参数为正数时代表cookie存在多少秒。
HttpServletResponse.addCookie(参数1,参数2):将创建好的cookie写入用户计算机。参数1代表cookie的名子,参数2代表cookie的值。
通过HttpServletRequest.getCookies()方法可以从相应用户读取cookie列表,放在cookie类型的数组中,通过数组中各个cookie的getName()和getValue()方法可以获取各个cookie的名称和值。