码迷,mamicode.com
首页 > 其他好文 > 详细

060_Cookie/Session

时间:2021-03-18 14:31:42      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:pos   utf-8   api   on()   lazy   exce   pattern   sch   instance   


会话

用户打开一个浏览器到关闭浏览器,这个过程可以称之为会话。

有状态会话

客户端再次访问服务端时,服务端知道客户端曾经来过,称之为有状态会话。

保存会话的两种技术

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

session

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

常见场景

  • 网站登录后,下次访问不需要登录

Cookie

  1. 服务端响应给客户端cookie
  2. 服务端从客户端请求中拿到cookie
Cookie[] cookies = req.getCookies();//获取cookie
cookie.getName();//获取cookie的key
cookie.getValue();//获取cookie的value
Cookie cookie = new Cookie("lastLoginTime",String.valueOf(System.currentTimeMillis()));//新建cookie
cookie.setMaxAge(24*60*60);//设置cookie有效期设置为1天
resp.addCookie(cookie);//响应给客户端一个cookie
  1. cookie一般会保存在本地的用户目录下的appData目录下

技术图片

<?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.qing</groupId>
  <artifactId>javaweb-cookie-session</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>
  </dependencies>
</project>

package com.qing.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;

/**
 * 保存用户上一次访问的时间
 */
public class CookieDemo01 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");

        PrintWriter out = resp.getWriter();

        //Cookie,服务端从客户端获取
        Cookie[] cookies = req.getCookies();//这里返回数组,说明cookie可能存在多个
        //判断cookie是否存在,第一次访问服务器时,不存在,cookie是由服务器给客户端的
        if (cookies == null || cookies.length < 1) {
            out.write("这是您第一次访问本站");
        } else {
            //如果存在,读取cookie,获取cookie中的值
            boolean flag = true;
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if ("lastLoginTime".equals(cookie.getName())) {
                    flag = false;
                    out.write("您上一次访问本站的时间是:");
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    out.write(new Date(lastLoginTime).toLocaleString());
                    System.out.println(new Date(lastLoginTime).toLocaleString());
                }
            }
            if (flag) {
                out.write("这是您第一次访问本站");
            }
        }
        //服务器给客户端响应一个cookie
        Cookie cookie = new Cookie("lastLoginTime",String.valueOf(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);
    }
}

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

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">

  <servlet>
    <servlet-name>cookieDemo01</servlet-name>
    <servlet-class>com.qing.servlet.CookieDemo01</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>cookieDemo01</servlet-name>
    <url-pattern>/cookie</url-pattern>
  </servlet-mapping>
</web-app>

cookie细节

  1. 一个cookie只能保存一个信息
  2. 一个web站点可以给浏览器发送多个cookie,每个站点最多存放20个cookie
  3. cookie大小有限制,一般为4kb
  4. 浏览器存放cookie一般最多300

删除cookie

  1. 不设置有效期,关闭浏览器,自动失效
  2. 设置有效期为0

Session

什么是session

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

session使用场景

  1. 保存登录用户的信息
  2. 购物车信息
  3. 在整个网站中经常使用的数据,我们将它保存在session中

session和cookie的区别

  1. cookie是把要保存的数据写给浏览器,浏览器保存(可以保存多个)
  2. session是把要保存的数据写的用户独占的session中,服务器保存(只保存重要的信息,减少服务器资源的浪费)
package com.qing.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

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","清风");

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

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

    }

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

package com.qing.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

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();

        //从session中取数据
        String name = (String) session.getAttribute("name");
        System.out.println(name);
    }

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

package com.qing.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionDemo03 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.invalidate();
    }

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

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

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">

  <servlet>
    <servlet-name>cookieDemo01</servlet-name>
    <servlet-class>com.qing.servlet.CookieDemo01</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>cookieDemo01</servlet-name>
    <url-pattern>/cookie</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>sessionDemo01</servlet-name>
    <servlet-class>com.qing.servlet.SessionDemo01</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>sessionDemo01</servlet-name>
    <url-pattern>/session1</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>sessionDemo02</servlet-name>
    <servlet-class>com.qing.servlet.SessionDemo02</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>sessionDemo02</servlet-name>
    <url-pattern>/session2</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>sessionDemo03</servlet-name>
    <servlet-class>com.qing.servlet.SessionDemo03</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>sessionDemo03</servlet-name>
    <url-pattern>/session3</url-pattern>
  </servlet-mapping>

  <!--设置session的默认失效时间-->
  <session-config>
    <!--15分钟后session自动失效,以分钟为单位-->
    <session-timeout>15</session-timeout>
  </session-config>
</web-app>

设置session自动过期在web.xml中

<!--设置session的默认失效时间-->
<session-config>
  <!--15分钟后session自动失效,以分钟为单位-->
  <session-timeout>15</session-timeout>
</session-config>

060_Cookie/Session

标签:pos   utf-8   api   on()   lazy   exce   pattern   sch   instance   

原文地址:https://www.cnblogs.com/wl3pb/p/14552778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!