首页 > 编程语言 >javaweb 7、Cookie、Session

javaweb 7、Cookie、Session

时间:2022-12-25 16:00:10浏览次数:38  
标签:session javaweb resp req Session cookie Cookie name

  1. 创建项目javaweb-session-cookie

2.补全目录java、resouces

  1. 更新web.xml
<?xml version="1.0" encoding="UTF-8"?>

<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">

</web-app>
  1. pom.xml更新依赖
<?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>com.binzaza</groupId>
  <artifactId>javaweb-session-cookie</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>5.0.0</version>
    </dependency>

    <dependency>
      <groupId>jakarta.servlet.jsp</groupId>
      <artifactId>jakarta.servlet.jsp-api</artifactId>
      <version>3.0.0</version>
    </dependency>
  </dependencies>

</project>

会话

会话:用户打开了一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话

有状态会话
一个网站,怎么证明你来过

  1. 服务器给客户端一个信件,客户端下次访问服务端带上信件就可以了 cookie
  2. 服务器登记你来过了,下次你来的时候我来匹配你 session

保存会话的两种技术

cookie

  • 客户端技术(响应,请求)

session

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

常见场景:网站登录之后,你下次不用再登录了,第二次访问就上去了

  1. 从请求中拿到cookie信息
  2. 服务器响应给客户端cookie
Cookie[] cookies = req.getCookies();  // 获得cookie
cookie.getName(); // 获得cookie中的key
cookie.getValue(); // 获取cookie中的value

Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+""); // 新建一个cookie

cookie.setMaxAge(24*60*60); // 设置cookie的有效期
resp.addCookie(cookie);

CookieDemo01.java

// 保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 服务器告诉你,你来的时间,把这个时间封装成一个信件,你下次带来,我就知道你来了

        // 中文乱码

        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();

        // Cookie,服务器端从客户端获取
        Cookie[] cookies = req.getCookies(); // 这里返回数组,说明cookie可能存在多个

        // 判断cookie是否存在
        if (cookies!=null){
            // 如果存在怎么办
            out.write("你上一次访问的时间是:");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                // 获取cookie的名字
                if (cookie.getName().equals("lastLoginTime")) {
                    // 获取cookie中的值
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write(date.toLocaleString());
                }
            }
        }else {
            out.write("这是您第一次访问本站");
        }
        // 服务器给客户端响应一个cookie
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
        // Cookie有效期为1天
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml

<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>CookieDemo01</servlet-name>
        <servlet-class>com.binzaza.servlet.CookieDemo01</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CookieDemo01</servlet-name>
        <url-pattern>/c1</url-pattern>
    </servlet-mapping>

</web-app>

浏览器访问:http://localhost:8080/c1

cookie: 一般会保存在本地的用户目录下

一个网站cookie是否存在上限!

  • 一个cookie只能保存一个信息;
  • 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie;
  • cookie大小限制4kb;
  • 300个浏览器上限;

删除cookie

  • 不设置有效期,关闭浏览器,自动失效;
  • 设置有效时间为0;
    CookieDemo02.java
public class CookieDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 创建一个cookie,名字必须要和要删除的名字一致
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");

        // 将Cookie 有小区设为0,立马过期
        cookie.setMaxAge(0);

        resp.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml

    <servlet>
        <servlet-name>CookieDemo02</servlet-name>
        <servlet-class>com.binzaza.servlet.CookieDemo02</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CookieDemo02</servlet-name>
        <url-pattern>/c2</url-pattern>
    </servlet-mapping>

启动访问:http://localhost:8080/c2

编码解码
CookieDemo03.java

// 中文数据传递
public class CookieDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 中文乱码
        resp.setContentType("text/html;charset=utf-8");

        Cookie[] cookies = req.getCookies();
        PrintWriter out = resp.getWriter();

        // 判断cookie是否存在
        if (cookies!=null) {
            // 如果存在怎么办
            out.write("你上一次访问的时间是:");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                // 获取cookie的名字
                if (cookie.getName().equals("name")) {
//                    System.out.println(cookie.getValue());
                    // 解码
                    out.write(URLDecoder.decode(cookie.getValue(),"UTF-8"));
                }
            }
        }else {
            out.write("这是您第一次访问本网站");
        }

        Cookie cookie = new Cookie("name", URLEncoder.encode("冰渣渣","utf-8"));
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml

<servlet>
    <servlet-name>CookieDemo03</servlet-name>
    <servlet-class>com.binzaza.servlet.CookieDemo03</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>CookieDemo03</servlet-name>
    <url-pattern>/c3</url-pattern>
</servlet-mapping>

访问地址:http://localhost:8080/c3

Session(重点)

什么是Session:

  • 服务器会给每一个用户(浏览器)创建一个Session对象
  • 一个session独占一个浏览器,只要浏览器没有关闭,这个session就存在
  • 用户登录之后,整个网站它都可以访问

Session和Cookie的区别

  • Cookie是把用户的呼叫写给用户的浏览器,浏览器保存(可以保存多个)
  • Session把用户的数据写到用户独占Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
  • Session对象由服务创建

给session存东西
SessionDemo01.java

public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决中文乱码
        resp.setContentType("text/html;charset=utf-8");

        // 得到Session
        HttpSession session = req.getSession();

        // 给Session中存东西
        session.setAttribute("name","冰渣渣");

        // 获取session的id
        String sessionId = session.getId();

        //判断session是不是新创建
        if (session.isNew()) {
            resp.getWriter().write("session创建成功,ID:"+sessionId);
        }else {
            resp.getWriter().write("session已经在服务器中存在了,ID:"+sessionId);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml

<servlet>
    <servlet-name>SessionDemo01</servlet-name>
    <servlet-class>com.binzaza.servlet.SessionDemo01</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SessionDemo01</servlet-name>
    <url-pattern>/s1</url-pattern>
</servlet-mapping>

访问地址:http://localhost:8080/s1

获取会话值
SessionDemo02.java

public class SessionDemo02 extends HttpServlet {
    @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");

        // 得到Session
        HttpSession session = req.getSession();

        String name = (String) session.getAttribute("name");
//        Object name = session.getAttribute("name");
        System.out.println(name);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml

<servlet>
    <servlet-name>SessionDemo02</servlet-name>
    <servlet-class>com.binzaza.servlet.SessionDemo02</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SessionDemo02</servlet-name>
    <url-pattern>/s2</url-pattern>
</servlet-mapping>

访问地址:http://localhost:8080/s2

创建一个Person对象
src\main\java\com\binzaza\pojo\Person.java

package com.binzaza.pojo;

public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

SessionDemo01.java

public class SessionDemo01 extends HttpServlet {
    @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");

        // 得到Session
        HttpSession session = req.getSession();

        // 给Session中存东西
        session.setAttribute("name",new Person("冰渣渣",20));

        // 获取session的id
        String sessionId = session.getId();

        //判断session是不是新创建
        if (session.isNew()) {
            resp.getWriter().write("session创建成功,ID:"+sessionId);
        }else {
            resp.getWriter().write("session已经在服务器中存在了,ID:"+sessionId);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

SessionDemo02.java

public class SessionDemo02 extends HttpServlet {
    @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");

        // 得到Session
        HttpSession session = req.getSession();

        Person person = (Person) session.getAttribute("name");
        System.out.println(person);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

访问地址:

  1. http://localhost:8080/s1
  2. http://localhost:8080/s2
null
Person{name='冰渣渣', age=20}

手动注销session
SessionDemo03.java

public class SessionDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("name");
        session.invalidate();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml

<servlet>
    <servlet-name>SessionDemo03</servlet-name>
    <servlet-class>com.binzaza.servlet.SessionDemo03</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SessionDemo03</servlet-name>
    <url-pattern>/s3</url-pattern>
</servlet-mapping>

先访问:http://localhost:8080/s1

http://localhost:8080/s2

http://localhost:8080/s3

最后访问http://localhost:8080/s2

null
Person{name='冰渣渣', age=20}
null

设置session失效时间
web.xml

<session-config>
    <!-- 15分钟后session自动失效,以分钟为单位 -->
    <session-timeout>15</session-timeout>
</session-config>

标签:session,javaweb,resp,req,Session,cookie,Cookie,name
From: https://www.cnblogs.com/zibinchen/p/17004133.html

相关文章