Cookie

Cookie

Cookie 是服务器通知客户端保存键值对的一种技术。客户端有了 Cookie 后,每次请求都发送给服务器。每个 Cookie 的大小不能超过 4kb

创建Cookie

在这里插入图片描述

CookieServlet.java

public class CookieServlet extends  BaseServlet{
    protected void createCookie(HttpServletRequest req, HttpServletResponse resp)throws Exception {
        //创建cookie对象
        Cookie cookie  = new Cookie("key1","cars");
        //通知客户端保存cookie
        resp.addCookie(cookie);
        resp.getWriter().write("Cookie is  OK");
    }
}

BaseServlet.java

package code;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public abstract class BaseServlet extends HttpServlet {

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

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决post请求中文乱码问题
        // 一定要在获取请求参数之前调用才有效
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        String action = req.getParameter("action");
        try {
            // 获取action业务鉴别字符串,获取相应的业务 方法反射对象
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
//            System.out.println(method);
            // 调用目标业务 方法
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

web.xml

<servlet>
    <servlet-name>CookieServlet</servlet-name>
    <servlet-class>code.CookieServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>CookieServlet</servlet-name>
    <url-pattern>/cookie</url-pattern>
</servlet-mapping>

服务器如何获取Cookie

服务器获取客户端的Cookie只需要一行代码:req.getCookies()得到的为Cookie数组

创建一个Cookie工具类

CookieUtils.java

package utils;

import javax.servlet.http.Cookie;

/**
 * @BelongsProject: JavaWeb
 * @BelongsPackage: CookieUtils
 * @Author: HeXin
 * @CreateTime: 2023/2/6  17:07
 * @Description:查询指定名称的cookie对象
 * @Version: 1.0
 */
public class CookieUtils {
	public static Cookie findCookie(String name,Cookie[] cookies) {
		if(name == null || cookies == null || cookies.length == 0){
			return null;
		}
		for(Cookie cookie : cookies){
			if(name.equals(cookie.getName())){
				return cookie;
			}
		}
		return null;
	}
}

Cookie值的修改

方案一

1、先创建一个要修改的同名(指的就是 key)的 Cookie 对象

2、在构造器,同时赋于新的 Cookie 值。

3、调用 response.addCookie( Cookie );

代码实现

protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //闯将一个要修改的同名Cookie对象
    //在构造器中赋予新的Cookie值
    Cookie cookie = new Cookie("key1","value0");
    //调用resp.addCookie( cookie )通知客户端保存修改
    resp.addCookie(cookie);
}

方案二

1、先查找到需要修改的 Cookie 对象

2、调用 setValue()方法赋于新的 Cookie 值。

3、调用 response.addCookie()通知客户端保存修改

代码实习

protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Cookie[] cookies = req.getCookies();
    //先查找到需要修改的Cookie对象
    Cookie cookie = CookieUtils.findCookie("key2",cookies);
    if(cookie != null){
        //调用setValue()方法赋于新的Cookie值
        cookie.setValue("key1");
        //调用resp.addCookie()通知客户端保存修改
        resp.addCookie(cookie);
    }
    resp.addCookie(cookie);
}

注:赋值时,值内不能包含汉字以及除字母以外的所有字符,如果必须要包含这些值,需要将字符集设置为BASE64

浏览器查看Cookie

在这里插入图片描述

Cookie生命控制

Cookie的生命控制指的是如何管理Cookie什么时候被销毁(删除)

Cookie其中包含一个可以控制生命周期的方法:

setMaxAge()

正数,表示在指定的秒数后过期

负数,表示当浏览器关闭,Cookie 就会被删除(默认值是-1)

零,表示马上删除 Cookie

代码演示

protected void defaultLife(HttpServletRequest req,HttpServletResponse resp)throws ServletException, IOException {
    Cookie cookie = new Cookie("keyLife","valueLife");
    cookie.setMaxAge(-1);
    resp.addCookie(cookie);
}

protected void lifeTime(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Cookie cookie = new Cookie("lifeTime","20");
    cookie.setMaxAge(20);//设置Cookie20秒后无效
    resp.addCookie(cookie);
}

protected void delete(HttpServletRequest req,HttpServletResponse resp)throws ServletException, IOException {
    //查询需要删除的Cookie
    Cookie cookie = CookieUtils.findCookie("key1",req.getCookies());
    cookie.setMaxAge(0);
    resp.addCookie(cookie);
}

Cookie有效路径Path的设置

Cookie的path属性可以有效的过滤哪些Cookie属性可以发送给服务器。哪些不发。path属性是通过请求的地址来进行有效的过滤。

代码演示

protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Cookie cookie = new Cookie("path1","value1");
    //getcontextpath是获得当前工程路径的方法
    cookie.setPath(req.getContextPath()+"/path");
    resp.addCookie(cookie);
}

联系:免输入用户名登录

代码演示

LoginServlet.java

package code;

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;

/**
 * @BelongsProject: JavaWeb
 * @BelongsPackage: LoginServlet
 * @Author: HeXin
 * @CreateTime: 2023/2/6  22:52
 * @Description:
 * @Version: 1.0
 */
public class LoginServlet extends HttpServlet {
	@Override
	protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		if("WLM".equals(username)&&"592506".equals(password)){
			//登录成功
			Cookie cookie = new Cookie("username", username);
			cookie.setMaxAge(60*60*24*15);//当前cookie在15天内有效
			resp.addCookie(cookie);
		}else{
			//登录失败
			System.out.println("登录失败");
		}
	}
}

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="http://localhost:8080/Cookie/login.jsp" method="get">
        用户名:<input type="text" name="username" value="${cookie.username.value}"><br/>
        密码:<input type="password" name="password"><br/>
        <input type="submit" value="登录">
    </form>
</body>
</html>

Session会话

定义

Session 就一个接口(HttpSession)。 Session 就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。 每个客户端都有自己的一个 Session 会话。 Session 会话经常用来保存用户登录之后的信息。

创建Seesion和获取(id号,是否为新)

如何创建和获取 Session。它们的 API 是一样的。

request.getSession()

​ 第一次调用是:创建 Session 会话

​ 之后调用都是:获取前面创建好的 Session 会话对象。

isNew() 判断到底是不是刚创建出来的(新的)

​ true 表示刚创建

​ false 表示获取之前创建

每个会话都有一个身份证号。也就是 ID 值。而且这个 ID 是唯一的。

getId() 得到 Session 的会话 id 值。

代码演示

SessionServlet.java

package code;

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

/**
 * @BelongsProject: JavaWeb
 * @BelongsPackage: SessionServlet
 * @Author: HeXin
 * @CreateTime: 2023/2/6  23:33
 * @Description:
 * @Version: 1.0
 */
public class SessionServlet extends BaseServlet{
	protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	    //创建和获取Session会话对象
		HttpSession session = req.getSession();
		//判断当前Session会话是否为新创建的
		boolean aNew = session.isNew();
		//获取Session会话的唯一标识
		String id = session.getId();
		resp.getWriter().write("得到的Session的id为:"+id+"<br/>");
		resp.getWriter().write("该Session是否是为新建的:"+aNew+"<br/>");
	}
}

html程序主要部分

<base href="http://localhost:8080/Cookie/">
<li><a href="session?action=createOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)</a></li>

Session域数据的存取

Session属于四大域中的一种,同样也可以存取数据。

代码演示

SessionServlet.java

/**
	 * @Description: 在Session中保存数据
	 * @CreateTime:2023/2/7 9:00
	 * @Author:HeXin
	 */
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.getSession().setAttribute("session","value");
}

/**
	 * @Description: 获取Session中的数据
	 * @CreateTime:2023/2/7 9:01
	 * @Author:HeXin
	 */
protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Object session = req.getSession().getAttribute("session");
    resp.getWriter().write("获取的数据:"+session);
}

html程序

<a href="session?action=setAttribute" target="target">Session域数据的存储</a>
<a href="session?action=getAttribute" target="target">Session域数据的获取</a>

Session生命周期控制

public void setMaxInactiveInterval(int interval) 设置 Session 的超时时间(以秒为单位),超过指定的时长,Session 就会被销毁。

​ 值为正数的时候,设定 Session 的超时时长。

​ 负数表示永不超时(极少使用)

public int getMaxInactiveInterval() 获取 Session 的超时时间

public void invalidate() 当前 Session 会话立刻超时无效。

Session 默认的超时时间长为 30 分钟。 因为在 Tomcat 服务器的配置文件 web.xml中默认有以下的配置,它就表示配置了当前 Tomcat 服务器下所有的 Session 超时配置默认时长为:30 分钟。

如果需要修改web工程下所有Session的超时时长,可以在自己的web工程下的web.xml文件中进行配置,修改之后需要重启服务器才会生效

<session-config>
    <!--默认值为30(分钟)-->
    <session-timeout>10</session-timeout>
</session-config>

如果需要修改个别Session的超时时长,则需要使用上述方法来实现

浏览器和Session之间关联

Session 技术,底层其实是基于 Cookie 技术来实现的。
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值