核心代码:
cookie.jsp
<body>
<%
Cookie thisCookie = null;
boolean cookieFound = false;
Cookie[] cookies = request.getCookies();
if(cookies!=null){
for(int i=0;i < cookies.length;i++){
thisCookie = cookies[i];
if(thisCookie.getName().equals("CookieCount")){
cookieFound = true;
break;
}
}
}
out.println("<h1>Cookie 计数器</h1>");
if(cookieFound){
int cookieCount = Integer.parseInt(thisCookie.getValue());
cookieCount++;
out.println("这是1分钟内第"+cookieCount+"次访问本页");
thisCookie.setValue(String.valueOf(cookieCount));
thisCookie.setMaxAge(60*1);
response.addCookie(thisCookie);
}
if(cookieFound==false){
out.println("你在近1分钟内没有访问过此页,现在是第一次访问");
thisCookie = new Cookie("CookieCount","1");
thisCookie.setMaxAge(60*1);
response.addCookie(thisCookie);
}
%>
</body>
cookieIndex.jsp
<body>
<%
String strUser=null;
String strPass=null;
boolean cookieFound = false;
//获取Cookie信息,并将值传入文本框
Cookie[] cookies = request.getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equals("user")){
strUser = cookies[i].getValue();
}
if(cookies[i].getName().equals("pass")){
strPass = cookies[i].getValue();
}
}
if(strUser!=null && strPass!=null){
cookieFound = true;
out.println(strUser);
out.println(strPass);
}
}
//实现页面跳转
if(cookieFound){
out.println("自动登录");
//response.sendRedirect("cookie.jsp");
}
//若没有Cookie,则创建Cookie对象.
//if...else if...替代多层if嵌套。
if(cookieFound==false){
strUser = (String)request.getParameter("user");
strPass = (String)request.getParameter("pass");
String strRecode = (String)request.getParameter("recode");
//判断是否勾选记住密码,及密码验证(字符是否为空,是否匹配,是否记住,创建Cookie)
if(strUser!=null && strPass!=null){
if(strUser.equals("xue") && strPass.equals("123")){
if(strRecode == null){
strRecode="";
}else if(strRecode.equals("recode")){
Cookie user = new Cookie("user",strUser);
Cookie pass = new Cookie("pass",strPass);
user.setMaxAge(30);
user.setMaxAge(30);
response.addCookie(user);
response.addCookie(pass);
out.println("记住密码成功");
}
response.sendRedirect("cookie.jsp");
}else{
out.println("密码错误");
}
}else{
strUser="";
strPass="";
}
}
%>
<form action="">
用户名:<input type="text" name="user" value="<% if(strUser!=null) out.println(strUser);%>" /><br>
密码:<input type="text" name="pass" value="<% if(strPass!=null) out.println(strPass);%>" /><br>
记住密码:<input type="checkbox" value="recode" name="recode"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>