其他分享
首页 > 其他分享> > Cookie&Seesion

Cookie&Seesion

作者:互联网

Cookie&Seesion

一、会话

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

有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,这就是有状态会话

一个网站,怎么证明你来过

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

二、保存会话的两种技术

1、Cookie

2、Seesion

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

三、Cookie

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

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

案例

package com.jhoves.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");

        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("lastLogonTime")){
                    //获取cookie中的值
                    long lastLogonTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLogonTime);
                    out.write(date.toLocaleString());
                }
            }
        }else{
            out.write("这是您第一次访问本站");
        }

        //服务器给客户端响应一个cookie
        Cookie cookie = new Cookie("lastLogonTime", System.currentTimeMillis()+"");
        resp.addCookie(cookie);

        //cookie有效期为一天
        cookie.setMaxAge(24*60*60);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
    <servlet>
        <servlet-name>CookieDemo01</servlet-name>
        <servlet-class>com.jhoves.servlet.CookieDemo01</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CookieDemo01</servlet-name>
        <url-pattern>/c1</url-pattern>
    </servlet-mapping>

一个网站cooki是否存在上限!(聊聊细节)

删除Cookie

编码解码:

//编码
URLEncoder.encode("文字","utf-8")
//解码
URLDecoder.decode(cookie.getValue(),"utf-8")

案例

package com.jhoves.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.net.URLDecoder;
import java.net.URLEncoder;

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

        //解决中文乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        //Cookie,服务器从客户端获取
        Cookie[] cookies = req.getCookies();   //这里返回数组,说明cookie存在多个
        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")){
                    //解码
                    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);
    }
}

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

四、Session(重点)

什么是Seesion:

Session和Cookie的区别:

使用场景:

使用Session:

package com.jhoves.pojo;
 
//创建了一个Person对象
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 +
                '}';
    }
}

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

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

        //给Session中存东西
        session.setAttribute("name",new Person("俊鸿",1));

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

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

        //Session创建的时候做了什么事情
//        Cookie cookie = new Cookie("JSESSIONID",sessionId);
//        resp.addCookie(cookie);

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

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

package com.jhoves.servlet;

import com.jhoves.pojo.Person;

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-16");
        resp.setCharacterEncoding("utf-16");
        resp.setContentType("text/html;charset=utf-8");

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

        //手动注销
        session.invalidate();
    }

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

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

标签:resp,req,cookie,Seesion,import,Cookie,servlet
来源: https://www.cnblogs.com/JHoves/p/15977925.html