zoukankan      html  css  js  c++  java
  • java--cookie获取上次登录时间

    package com.test;

    import java.io.IOException;
    import java.util.Date;

    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import com.test.util.cookieUtil;

    public class demo_04 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	response.setContentType("text/html;charset=utf-8");
    	String username=request.getParameter("username");
    	String passwd=request.getParameter("passwd");
    	if("admin".equals(username)&& "123".equals(passwd)) {
    		Cookie[] cookies = request.getCookies();
    		Cookie cookie= cookieUtil.findCookie(cookies, "last");
    		if(cookie == null) {
    			Cookie c = new Cookie("last",System.currentTimeMillis()+"");
    			c.setMaxAge(60);
    			response.addCookie(c);
    			response.getWriter().write("welcome, "+ username);
    		}else {
    			// String vaule = cookie.getValue();
    			long lastVisit= Long.parseLong(cookie.getValue());
    			response.getWriter().write("welcome, "+ username+"上次登录时间是:"+new Date(lastVisit));
                                cookie.setValue(System.currentTimeMillis()+"");
    			response.addCookie(cookie);
    		}
    		System.out.println("success");
    		//response.getWriter().write("welcome, "+ username);
    	}else {
    		System.out.println("falid");
    	}
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	doGet(request, response);
    }
    

    }
    ###################################################################################
    package com.test.util;

    import javax.servlet.http.Cookie;

    public class cookieUtil {
    public static Cookie findCookie(Cookie[] cookies,String name) {
    if(cookies !=null) {
    for (Cookie cookie : cookies) {
    if(name.equals(cookie.getName())) {
    return cookie;
    }
    }
    }
    return null;

    }
    

    }

    Insert title here

    请输入一下内容:

    账号:
    密码:
    ******************************人因为有理想、梦想而变得伟大,而真正伟大就是不断努力实现理想、梦想*****************************
  • 相关阅读:
    java移位的具体应用
    mysql计划任务(轮询执行脚本)
    算法题(1)
    transient关键字及Serializable的序列化与反序列化
    java后台调用短信接口,实现发送短信验证码的控制层实现
    防卫导弹
    C++ STL
    字母转换
    三分·三分求极值
    各种数据类型取值范围
  • 原文地址:https://www.cnblogs.com/cloudLi/p/13208842.html
Copyright © 2011-2022 走看看