有关Cookie的一些操作。
(1)取得cookie的相关信息
Cookie[] cookies = request.getCookies();
String username = "";
String password = "";
if(cookies!=null) {
for(int i=0;i<cookies.length;i++){
Cookie c = cookies[i];
if("admin".equals(c.getName()))username = c.getValue();
else if("admin".equals(c.getName()))password = c.getValue();
}
}
(2)将登陆用户的名和密码保存到Cookie中(在服务器端)
Cookie cookieUsername = new Cookie("username","admin");
Cookie cookiePassword = new Cookie("password","admin");
cookieUsername.setMaxAge(60*60);//设定有效时间
cookieUsername.setPath("/");
cookiePassword.setPath("/");
cookieUsername.setDomain(".XXX.XX.XX")//设定有效域
cookiePassword.setDomain(".XXX.XX.XX")
response.addCookie(cookieUsername);
response.addCookie(cookiePassword);
(3)退出登陆的时候将cookie删除
Cookie[] cookies = request.getCookies();
try{
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
String cookieName = cookies[i].getName();
if("username".equals(cookieName)||"password".equals(cookiename)){
cookies[i].setValue(null);
cookies[i].setPath("/");
cookies[i].setMagAge(0);
response.addCookie(cookies[i])
}
}
}
}catch(Exception e){
LogUtil.error(this.getClass(),e.getMessage(),e)
}
(1)取得cookie的相关信息
Cookie[] cookies = request.getCookies();
String username = "";
String password = "";
if(cookies!=null) {
for(int i=0;i<cookies.length;i++){
Cookie c = cookies[i];
if("admin".equals(c.getName()))username = c.getValue();
else if("admin".equals(c.getName()))password = c.getValue();
}
}
(2)将登陆用户的名和密码保存到Cookie中(在服务器端)
Cookie cookieUsername = new Cookie("username","admin");
Cookie cookiePassword = new Cookie("password","admin");
cookieUsername.setMaxAge(60*60);//设定有效时间
cookieUsername.setPath("/");
cookiePassword.setPath("/");
cookieUsername.setDomain(".XXX.XX.XX")//设定有效域
cookiePassword.setDomain(".XXX.XX.XX")
response.addCookie(cookieUsername);
response.addCookie(cookiePassword);
(3)退出登陆的时候将cookie删除
Cookie[] cookies = request.getCookies();
try{
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
String cookieName = cookies[i].getName();
if("username".equals(cookieName)||"password".equals(cookiename)){
cookies[i].setValue(null);
cookies[i].setPath("/");
cookies[i].setMagAge(0);
response.addCookie(cookies[i])
}
}
}
}catch(Exception e){
LogUtil.error(this.getClass(),e.getMessage(),e)
}