Cookie显示上一次登录时间

案例:记住上一次访问时间
	1. 需求:
		1. 访问一个Servlet,如果是第一次访问,则提示:您好,欢迎您首次访问。
		2. 如果不是第一次访问,则提示:欢迎回来,您上次访问时间为:显示时间字符串

代码实现1

package com.demos;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

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

/**
 *  案例:记住上一次访问时间
		1. 需求:
			1. 访问一个Servlet,如果是第一次访问,则提示:您好,欢迎您首次访问。
			2. 如果不是第一次访问,则提示:欢迎回来,您上次访问时间为:显示时间字符串
 * Servlet implementation class LastCookie
 */
@WebServlet(name = "lastCookie", urlPatterns = { "/lastCookie" })
public class LastCookie extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		
		//获取所有的Cookie
		Cookie[] cookies = request.getCookies();
		boolean flag = false;//没有cookie为lastTime
		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				//获取cookie名字
				String name = cookie.getName();
				//判断名称是否是: lastCookie
				if ("lastTime".equals(name)) {
					//又该Cookie,不是第一次访问
					flag = true;
					
					 //设置Cookie的value
                    //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
                    Date date  = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String str_date = sdf.format(date);
                    System.out.println("编码前:"+str_date);
                    //URL编码
                    str_date = URLEncoder.encode(str_date,"gbk");
                    System.out.println("编码后:"+str_date);
                    cookie.setValue(str_date);
                    //设置cookie的存活时间
                    cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
                    response.addCookie(cookie);
					
                    //响应数据
                    //获取Cookie的value,时间
                    String value = cookie.getValue();
                    System.out.println("解码前:"+value);
                    //URL解码:
                    value = URLDecoder.decode(value,"gbk");
                    System.out.println("解码后:"+value);
                    response.getWriter().write("<h1>欢迎回来,您上次访问时间为:"+value+"</h1>");
				}
			}
					
		}
		

        if(cookies == null || cookies.length == 0 || flag == false){
            //没有,第一次访问

            //设置Cookie的value
            //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
            Date date  = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String str_date = sdf.format(date);
            System.out.println("编码前:"+str_date);
            //URL编码
            str_date = URLEncoder.encode(str_date,"gbk");
            System.out.println("编码后:"+str_date);

            Cookie cookie = new Cookie("lastTime",str_date);
            //设置cookie的存活时间
            cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
            response.addCookie(cookie);

            response.getWriter().write("<h1>您好,欢迎您首次访问</h1>");
        }

	}

}

代码jsp实现

<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>demo</title>
</head>
<body>

<%

    //1.获取所有Cookie
    Cookie[] cookies = request.getCookies();
    boolean flag = false;//没有cookie为lastTime
    //2.遍历cookie数组
    if(cookies != null && cookies.length > 0){
        for (Cookie cookie : cookies) {
            //3.获取cookie的名称
            String name = cookie.getName();
            //4.判断名称是否是:lastTime
            if("lastTime".equals(name)){
                //有该Cookie,不是第一次访问

                flag = true;//有lastTime的cookie

                //设置Cookie的value
                //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
                Date date  = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                String str_date = sdf.format(date);
                System.out.println("编码前:"+str_date);
                //URL编码
                str_date = URLEncoder.encode(str_date,"utf-8");
                System.out.println("编码后:"+str_date);
                cookie.setValue(str_date);
                //设置cookie的存活时间
                cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
                response.addCookie(cookie);


                //响应数据
                //获取Cookie的value,时间
                String value = cookie.getValue();
                System.out.println("解码前:"+value);
                //URL解码:
                value = URLDecoder.decode(value,"utf-8");
                System.out.println("解码后:"+value);
                %>
            <h1>欢迎回来,您上次访问时间为:<%=value%></h1>
            <input>

<%



                break;

            }
        }
    }


    if(cookies == null || cookies.length == 0 || flag == false){
        //没有,第一次访问

        //设置Cookie的value
        //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
        Date date  = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String str_date = sdf.format(date);
        System.out.println("编码前:"+str_date);
        //URL编码
        str_date = URLEncoder.encode(str_date,"utf-8");
        System.out.println("编码后:"+str_date);

        Cookie cookie = new Cookie("lastTime",str_date);
        //设置cookie的存活时间
        cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
        response.addCookie(cookie);

%>

        <h1>您好,欢迎您首次访问</h1>
<span></span>

<%
    }

%>

<input>




</body>
</html>

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的自动登录显示一次登录时间cookie程序的示例: ```python import datetime import http.cookies import os import sys def get_last_login_time(): # 从 cookie获取一次登录时间 cookie_str = os.environ.get('HTTP_COOKIE') if cookie_str: cookie = http.cookies.SimpleCookie() cookie.load(cookie_str) if 'last_login_time' in cookie: last_login_time = cookie['last_login_time'].value return datetime.datetime.strptime(last_login_time, '%Y-%m-%d %H:%M:%S') return None def set_last_login_time(): # 设置当前时间登录时间,并将登录时间保存到 cookie 中 now = datetime.datetime.now() cookie = http.cookies.SimpleCookie() cookie['last_login_time'] = now.strftime('%Y-%m-%d %H:%M:%S') print(cookie.output()) def main(): # 获取一次登录时间显示 last_login_time = get_last_login_time() if last_login_time: print('上一次登录时间为:{}'.format(last_login_time)) else: print('这是您第一次登录') # 设置当前时间登录时间,并将登录时间保存到 cookie 中 set_last_login_time() if __name__ == '__main__': main() ``` 该程序的实现方式是通过读取 HTTP 请求的 cookie 头部来获取一次登录时间,并在登录成功后将当前时间保存到 cookie 中。程序中使用了 Python 的 `http.cookies.SimpleCookie` 类来处理 cookie,该类可以方便地将 cookie 转换为字符串,并且可以通过属性或方法来访问 cookie 中的键值对。需要注意的是,由于 cookie 可能会被篡改或伪造,因此在实际应用中需要进行相应的安全措施来保护 cookie 的安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值