其他分享
首页 > 其他分享> > 12-Cookie

12-Cookie

作者:互联网

12-Cookie

概述

终于学到了最想了解的Cookie和Session了,其实这些概念很简单,,强烈推荐狂神说的视频 把Cookie讲的十分简单
Cookie,是曲奇饼
思考一下,
学校如何知道你是这个学校的学生?

  1. 你出示校园卡
  2. 学校到系统里面去查你的学号
    那服务器如何知道一个客户端来过?
  3. 第一次你来给你一个信件, 下次来的时候带上;Cookie
  4. 服务器登记你来过了, 下次你来的时候我来匹配你;即Session

什么是会话?

会话:用户打开了一个浏览器,点击了很多超链接,访问了多个web资源,关闭浏览器,这个过程可以称之为一次会话
有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学曾经来过,称之为有状态会话

保存会话的技术

Cookie
客户端技术
Session
服务器技术,利用这个技术,可以保存用户的会话信息,我们可以把信息或者数据放在Session中

常见场景,网站登陆后,下次不用再登录,第二次可以直接上去

  1. 从请求中拿到cookie信息
    Cookie[] cookies = req.getCookies();
    
  2. 服务器响应给客户端
    cookie.getName() // 获取cookie名字
    cookie.getValue() // 获取cookie值
    Cookie lastLoginTime = new Cookie("LastLoginTime", System.currentTimeMillis() + ""); // 创建Cookie
    lastLoginTime.setMaxAge(24 * 60 * 60); // 设置cookie过期时间
    resp.addCookie(lastLoginTime); // 响应添加cookie
    

Cookie过期时间探讨

lastLoginTime.setMaxAge(24 * 60 * 60); // 过期时间为一天,关闭浏览器cookie不会失效
lastLoginTime.setMaxAge(0); // 过期时间为0秒,即删除cookie
lastLoginTime.setMaxAge(-1); // 默认过期时间,即关闭浏览器cookie失效

思考? 一个网站cookie是否存在上限

实践

CookieServlet.java

package com.kuang.servlet;

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 java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * 功能描述
 *
 * @since 2022-08-17
 */
public class CookieServlet extends HttpServlet {
    private static final long serialVersionUID = -2638465249548374476L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        Cookie[] cookies = req.getCookies();
        if (cookies == null) {
            writer.write("第一次访问该网站");
        } else {
            Boolean flag = Boolean.FALSE;
            System.out.println(cookies.length);
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("LastLoginTime")) {
                    long l = Long.parseLong(cookie.getValue());
                    flag = Boolean.TRUE;
                    writer.write("上次访问的时间为:" + new Date(l).toLocaleString());
                }
            }
            if (!flag) {
                writer.write("第一次访问该网站");
            }
        }
        Cookie lastLoginTime = new Cookie("LastLoginTime", System.currentTimeMillis() + "");
         lastLoginTime.setMaxAge(24 * 60 * 60);
//        lastLoginTime.setMaxAge(0);
        resp.addCookie(lastLoginTime);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0"
         metadata-complete="true">
    <servlet>
        <servlet-name>cookie</servlet-name>
        <servlet-class>com.kuang.servlet.CookieServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>cookie</servlet-name>
        <url-pattern>/cookie</url-pattern>
    </servlet-mapping>
</web-app>

子pom

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.example</groupId>
        <artifactId>JavaWeb-Study</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>06-Cookie</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>06-Cookie Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

</project>

父pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>JavaWeb-Study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>01-HelloServlet</module>
        <module>02-ServletContext</module>
        <module>03-Download</module>
        <module>04-VerificationCode</module>
        <module>05-Login</module>
        <module>06-Cookie</module>
    </modules>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
    </dependencies>

</project>

标签:12,import,resp,cookie,lastLoginTime,Cookie,servlet
来源: https://www.cnblogs.com/Oh-mydream/p/16597667.html