欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

cookie

程序员文章站 2024-03-20 13:33:52
...

创建cookie对象

Cookie newCookie= new Cookie(String key,Object value);

写入cookie对象

respone.addCookie(newCookie);

读取Cookie对象

Cookie[] cookies=request.getCookie();

案例—登录页面保存用户名和密码信息
login.jsp

<%
String username="";
String password="";
Cookie[] cookies=request.getCookie();
if(cookies!=null && cookies.length>0){
for(Cookie c:cookies){
if(c.getName().equals("username") ){
username=URLDecoder.decode(c.getValue());
}
if(c.getName.equals("password")){
password=URLDecoder.decode(c.getValue());
}
}
}
%>
<form name="loginForm" action="dologin.jsp" method="post">
<input type="text" name="username" value="<%=username %>"/>
<input type="password" name="password" value="<%=password %>"/>
<input type="checkbox" name="isUserCookie" checked="checked"/>
<input type="submit" name="submit" value="登录"/>
</form>

dologin.jsp

//导入java.net.*
<%
//首先判断用户是否选择了记录登录状态
String[] isUserCookies=request.getParamterValues("isUseCookie");
if(isUseCookies!=null && isUseCookies.length>0){
//把用户名和密码保存在Cookie对象中
String username=URLEncoder.encode(request.getParamter("username"));
String password=URLEncoder.encode(request.getParamter("password"));
Cookie usernameCookie=new Cookie("username");
Cookie passwordCookie=new Cookie("password");
usernameCookie.setMaxAge(864000);
passwordCookie.setMaxAge(860000);
response.addCookie(usernameCookie);
response.addCookie(passwordCookie);
}else{

Cookie[] cookies=request.getCookie();
if(cookies!=null && cookies.length>0){
for(Cookie c:cookies){
if(c.getName().equals("username") || c.getName.equals("password")){
c.setMaxAge(0);//设置cookie失效
response.addCookie(c);//重新保存cookies
}
}
}

}

%>
<a herf="user.jsp" target="_blank">查看用户名和密码</a>

user.jsp

<%
String username="";
String password="";
Cookie[] cookies=request.getCookie();
if(cookies!=null && cookies.length>0){
for(Cookie c:cookies){
if(c.getName().equals("username") ){
username=URLDecoder.decode(c.getValue());
}
if(c.getName.equals("password")){
password=URLDecoder.decode(c.getValue());
}
}
}
%>
用户名:<%=username %>
密码:<%= password %>