编程语言
首页 > 编程语言> > JavaWeb的Cookie、Session

JavaWeb的Cookie、Session

作者:互联网

Cookie、Session

1 会话

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

有状态会话

一个网站,证明证明你来过?

客户端 服务端

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

2 保存会话的两种技术

cookie

session

  1. 从请求中拿到cookie信息
  2. 服务器响应给客户端cookie
Cookie[] cookies = req.getCookies();//获得cookie
cookie.getName();//获得Cookie的key
cookie.getValue();//获得Cookie的Value
new Cookie("lastLoginTime", String.valueOf(System.currentTimeMillis()));//新建一个cookie
cookie.setMaxAge(24*60*60); //设置cookie有效期为一天
resp.addCookie(cookie);//响应设置的cookie到浏览器

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

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

删除Cookie

传递中文cookie

//编码
Cookie cookie = new Cookie("name",URLEncoder.encoded("测试","utf-8"));
//解码
out.write(URLDecoder.decode(cookie.getValue,"UTF-8"));

测试:

package com.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.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 {
        //服务器告诉你,你来的时间把这个时间封装成一个信件,你下带来,我就知道你来了

        //解决中文乱码
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("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")){
                   long lastLoginTime = Long.parseLong(cookie.getValue());
                   Date date = new Date(lastLoginTime);
                   out.write(date.toLocaleString());
               }
            }
        }else {
            out.write("这是你第一次访问本站");
        }

        //服务器给客户端响应一个cookie
        Cookie cookie = new Cookie("lastLoginTime", String.valueOf(System.currentTimeMillis()));
        //设置cookie有效期为一天
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    };

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

image

4 Session(重点)

什么是Session:

Session和Cookie的区别:

使用场景

常用方法

方法名 功能描述
getId() 获取SessionID
isNew() Session是否是新的(如果客户端请求消息中返回了一个与Servlet程序当前获得的HttpSession对象的会话标识号相同,则认为这个HttpSession对象不是新建的)
setMaxInactiveInterval() 设置Session的最大时效
getMaxInactiveInterval() 获取Session的最大时效
getCreationTime() 获取Session的创建时间
getLastAccessedTime() 获取Session的最后访问时间
invalidate() 销毁Session对象
setAttribute() 设置数据,将数据保存在Session这个域对象中
getAttribute() 获取数据,将保存在Session这个域对象中的数据获取出来

使用

  1. 创建测试类Person
package com.Pojo;

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

    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 "Pojo.Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
  1. 创建测试Session类
package com.servlet;
import com.Pojo.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

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

        //得到Session
        HttpSession session = req.getSession();
        //给Seesion中存东西
        session.setAttribute("name", new Person("测试",1));
        //获取Session的ID
        String sessionId = session.getId();

        //判断Session是不是新创建的
        if (session.isNew()) {
            resp.getWriter().write("session创建成功:"+sessionId);
        }else {

            resp.getWriter().write("session已创建的ID:"+sessionId);
        }
        Person person= (Person) session.getAttribute("name");

        resp.getWriter().write("</br>");
        resp.getWriter().write(String.valueOf(person));
    }

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

image

  1. 新页面引用Session类
package com.servlet;

import com.Pojo.Person;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

public class SessionDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("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. 注销Session年

    1. 手动注销
    package com.servlet;
    
    import jakarta.servlet.ServletException;
    import jakarta.servlet.http.HttpServlet;
    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.servlet.http.HttpServletResponse;
    import jakarta.servlet.http.HttpSession;
    
    import java.io.IOException;
    
    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);
        }
    }
    
    1. 自动注销

    web.xml中写入

    <!--    设置session默认的失效时间-->
        <session-config>
    <!--        十五分钟自动注销-->
            <session-timeout>15</session-timeout>
        </session-config>
    

标签:JavaWeb,jakarta,resp,Session,cookie,import,Cookie,servlet
来源: https://www.cnblogs.com/xiangsir/p/16264722.html