//登陆显示上次登陆的时间
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//使用Cookie对上次登陆时间进行记录
public class CookiesTest extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//从客户端获取web服务器相关的cookie信息
Cookie[] cookies = request.getCookies();
//定义用于存放时间值
String time="";
//有无此类型的Cookie的标识
Boolean flag=false;
//客户端存在类型的Cookie,进行一步的判断
if(cookies!=null && cookies.length>0){
//循环cookie
for(Cookie c:cookies){
//当需要的cookie拿到之后
if("lastTime".equals(c.getName())){
//就取出相应的内容
time=c.getValue();
flag=true;
//断开
break;
}
}
out.println("您上次的登陆时间"+time);
}else{
if(!flag){
//加入是第一次的话,输出提示
out.println("欢迎您的到来");
//添加Cookie
Cookie cook=new Cookie("lastTime",new java.util.Date().toLocaleString());
cook.setMaxAge(1*60);
response.addCookie(cook);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
在表单中选择是否保存相应的账户信息:
package com.xh.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieForRecord extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取账户名
String uname = request.getParameter("uname");
//获取相应的密码
String pwd = request.getParameter("pwd");
//获取是否保存密码
String keepPwd = request.getParameter("keepPwd");
//获取是否保存账户名
String keepUname = request.getParameter("keepUname");
if(keepPwd!=null && keepPwd.equals("keepPwd")){
//要求保存密码的时候,产生相应的Cookie
Cookie cookie = new Cookie("pwd",pwd);
//切记向客户端发送相应的响应
response.addCookie(cookie);
}
//当没有获得保存的要求的时候,执行删除Cookie操作
if(keepPwd==null){
deleteCookie(request, response, "pwd");
}
if(keepUname!=null && keepUname.equals("keepUname")){
Cookie cookie = new Cookie("uname",uname);
response.addCookie(cookie);
}
if(keepUname==null){
deleteCookie(request, response, "uname");
}
response.sendRedirect("/doWeb/index.jsp");
}
private void deleteCookie(HttpServletRequest request,HttpServletResponse response,String key){
Cookie[] cookies = request.getCookies();
if(cookies!=null){
//迭代循环相应的Cookie
for(Cookie c:cookies){
//获取到相应的Cookie后
if(c.getName().equals(key)){
//设置生命周期为0
c.setMaxAge(0);
//发送到客户端
response.addCookie(c);
break;
}
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}