Cookie中用户登录信息的提示

public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");

request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
System.out.println("调用后台实现正常登录的功能:"+name+","+pwd);

//下面实现显示用户上次登录的功能
String showTime = func(request,response);
out.println(name+","+showTime);

out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

//模块:实现显示用户上次登录的功能
private String func(HttpServletRequest request, HttpServletResponse response) {
String showTime="您最近是第一次登录!";
//所获客户端的所有cookie
Cookie cs[] = request.getCookies();
if(cs!=null){
for(Cookie c:cs){
if(c.getName().equals("loginTime")){
String str = c.getValue();
long tm = Long.parseLong(str);
Date d = new Date(tm);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
showTime = "您上次登录时间为: "+sdf.format(d);
break;
}
}
}

//不管之前是否已经存在该cookie,都要重新添加一次,因为:若没有则要添加新的,若已有则要更新旧的(把新的登录时间记录进去)
//添加一个新的 或 修改旧的 用于记录当前登录时间的cookie---loginTime
Date d = new Date();
long tm = d.getTime();
Cookie coo = new Cookie("loginTime",""+tm);
coo.setMaxAge(60*60*24*30);//秒为单位 有效期为:1个月
coo.setPath("/"); //设为项目根目录,这样我们项目中所有servlet或jsp都可以访问。但其它项目是不能访问我们的cookie的
response.addCookie(coo); //添加即是写到客户端

return showTime;
}

------------------------------------------------------------------------------------------------------------------------------------------------

 

<h3>用cookie技术实现显示用户上次登录时间</h3>
<form action="LoginServlet" method="post">
姓名:<input type="text" name="name"/> <br/>
密码:<input type="password" name="pwd"/> <br/>
<input type="submit" value="登录"/>
</form>

posted @ 2016-10-12 09:41  折腾青春  阅读(1345)  评论(0编辑  收藏  举报