01-Cookie&Session2

简介: 01-Cookie&Session2

g) Cookie 有效路径Path的设置

Cookie的path属性可以有效的过滤哪些Cookie可以发送给服务器。哪些不发。

path属性是通过请求的地址来进行有效的过滤。
CookieA path=/工程路径

CookieB path=/工程路径/abc


请求地址如下:

http://ip:port/工程路径/a.html

CookieA发送

CookieB不发送

http://ip:port/工程路径/abc/a.html

CookieA发送

CookieB发送

修改 cookie.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.O1 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" kontent="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="content-Type" content="text/html; charset=UTF-8">
<title>Cookie</title>
    <base href="http://localhost:8080/13_cookie_session/">
    <style type="text/css">
        ul li{
            list-style:none;
        }
    </style>
</head>
<body>
<iframe name="target" width="500"  height="500" style="..."></iframe>
    <div style="...">
        <ul>
            <li><a href="cookieServlet?action=createCookie" target="target">Cookie的创建</a></li>
            <li><a href="cookieServlet?action=getCookie" target="target">cookie的获取</a></li>
            <li><a href="cookieServlet?action=updateCookie" target="target">cookie值的修改</a></li>
            <li>cookie的存活周期</li>
            <li>
                <ul>
                    <li><a href="cookieServlet?action=defaultLife" target="target">cookie的默认存活时间(会话)</a></li>
                    <li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即删除</a></li>
                    <li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小时)</a></li>
                </ul>
            </li>
            <li><a href="cookieServlet?action=testPath" target="target">Cookie的路径设置</a></li>
            <li><a href="" target="target">Cookie的用户免登录练习</a></li>
        </ul>
    </div>
</body>
</html>

修改

package com.servlet;
import com.util.CookieUtils;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieServlet extends BaseServlet {
    protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 创建Cookie对象
        Cookie cookie = new Cookie("key1", "value1");
        //2 通知客户端保存Cookie
        resp.addCookie(cookie);
        //1 创建Cookie对象
        Cookie cookie2 = new Cookie("key2", "value2");
        //2 通知客户端保存Cookie
        resp.addCookie(cookie2);
        //1 创建Cookie对象
        Cookie cookie3 = new Cookie("key3", "value3");
        //2 通知客户端保存Cookie
        resp.addCookie(cookie3);
        resp.getWriter().write("Cookie创建成功");
    }
    protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            //getName  方法返回Cookie的key(名)
            //getValue 方法返回Cookie的value(值)
            resp.getWriter().write("Cookie["+cookie.getName()+"="+cookie.getValue()+"]<br>");
        }
        Cookie iWantCookie = CookieUtils.findCookie("key1",cookies);
//        for (Cookie cookie : cookies) {
//            if ("key2".equals(cookie.getName())){
//                iWantCookie=cookie;
//                break;
//            }
//        }
        //如果不等于null,说明赋过值,也就是找到了需要的Cookie
        if (iWantCookie!=null){
            resp.getWriter().write("找到了需要的Cookie");
        }
    }
    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        方案一
        1、先创建一个要修改的同名的Cookie对象
        2、在构造器,同时赋于新的Cookie值。
//        Cookie cookie=new Cookie("key1","newValue1");
        3、调用response.addCookie( Cookie );//通知客户端保存修改
//        resp.addCookie(cookie);
//        resp.getWriter().write("key1的Cookie已经修改好");
//        方案二:
//        1、先查找到需要修改的Cookie对象
        Cookie cookie=CookieUtils.findCookie("key2",req.getCookies());
        if (cookie!=null){
//        2、调用setValue()方法赋于新的Cookie值。
        cookie.setValue("newValue2");
//        3、调用response.addCookie()通知客户端保存修改
            resp.addCookie(cookie);
        }
        resp.getWriter().write("key2的Cookie已经修改好");
    }
    protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie=new Cookie("defaultLife","defaultLife");
        cookie.setMaxAge(-1);//设置存活时间
        resp.addCookie(cookie);
    }
    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //先找到你要删除的Cookie对象
        Cookie cookie=CookieUtils.findCookie("key3",req.getCookies());
        if (cookie!=null){
            //调用setMaxAge(0)
            cookie.setMaxAge(0);//表示马上删除,都不需要等待浏览器关闭
            //调用response.addCookie( Cookie )
            resp.addCookie(cookie);
            resp.getWriter().write("key3的Cookie已经被删除");
        }
    }
    protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //先找到你要删除的Cookie对象
        Cookie cookie=new Cookie("life3600","life3600");
        cookie.setMaxAge(60*60);//设置Cookie一小时之后被删除,无效
        resp.addCookie(cookie);
        resp.getWriter().write("已经创建了一个存活一小时的Cookie");
    }
    protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie=new Cookie("path1","path1");
        //getContextPath()-->得到工程路径
        cookie.setPath(req.getContextPath()+"/abc");//----》工程路径/abc
        resp.addCookie(cookie);
        resp.getWriter().write("创建了一个带有Path路径的Cookie");
    }
}



h) Cookie 练习——免输入用户名登录



创建 LoginServlet,并配置web.xml

package com.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;
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 ("wzg168".equals(username)&&"123456".equals(password)){
            //登录成功
            Cookie cookie=new Cookie("username",username);
            cookie.setMaxAge(60*60*24*7);//当前Cookie一周内有戏
            resp.addCookie(cookie);
            System.out.println("登录成功");
        }else {
            //登录失败
            System.out.println("登录失败");
        }
    }
}

创建 login.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/8/24
  Time: 下午 02:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="http://localhost:8080/13_cookie_session/loginServlet" 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>

结果

访问http://localhost:8080/13_cookie_session/login.jsp

登录成功以后关闭浏览器,再次访问


2、Session 会话

视频

准备

创建web/session.html

<!DocTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//en" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="pragma" content="no-cache" />
    <meta http-equiv="cache-control" content="no-cache"/>
    <meta http-equiv="Expires" content="0" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Session</title>
    <style type="text/css">
        ul li{
            list-style:none;
        }
    </style>
</head>
<body>
    <iframe name="target" width="500" height="500" style="..."></iframe>
    <div style="...">
        <ul>
            <li><a href="" target="target">Session的创建和获取(id号、是否为新创建)</a></li>
            <li><a href="" target="target">session域数据的存储</a></li>
            <li><a href="" target="target">Session域数据的获取</a></li>
            <li>session的存活</li>
            <li>
                <ul>
                    <li><a href="" target="target">Session的默认超时及配置</a></li>
                    <li><a href="" target="target">session3秒超时销毁</a></li>
                    <li><a href="" target="target">Session马上销毁</a></li>
                </ul>
            </li>
            <li><a href="" target="target">浏览器和Session绑定的原理</a></li>
        </ul>
    </div>
</body>
</html>

i) 什么是Session会话?

1、Session就一个接口(Httpsession)。

2、Session就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。
3、每个客户端都有自己的一个session会话。

4、Session会话中,我们经常用来保存用户登录之后的信息。

j) 如何创建Session和获取(id号,是否为新) 如何创建和获取session。它们的API是一样的。

request.getSession()

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

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


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

true表示刚创建

false表示获取之前创建


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

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

创建SessionServlet,并在web.xml配置

package com.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionServlet extends BaseServlet{
    protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建和获取Session会话对象
        HttpSession session = req.getSession();
        //判断 当前session回滚,是否是新创建出来的
        boolean isNew = session.isNew();
        //获取session会话的唯一标识 id
        String id = session.getId();
        resp.getWriter().write("得到的Session,它的id是:"+id+"<br/>");
        resp.getWriter().write("这个Session是否是新创建的:"+isNew+"<br/>");
    }
}

修改 session.html

<!DocTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//en" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="pragma" content="no-cache" />
    <meta http-equiv="cache-control" content="no-cache"/>
    <meta http-equiv="Expires" content="0" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Session</title>
    <base href="http://localhost:8080/13_cookie_session/">
    <style type="text/css">
        ul li{
            list-style:none;
        }
    </style>
</head>
<body>
    <iframe name="target" width="500" height="500" style="..."></iframe>
    <div style="...">
        <ul>
            <li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)</a></li>
            <li><a href="" target="target">session域数据的存储</a></li>
            <li><a href="" target="target">Session域数据的获取</a></li>
            <li>session的存活</li>
            <li>
                <ul>
                    <li><a href="" target="target">Session的默认超时及配置</a></li>
                    <li><a href="" target="target">session3秒超时销毁</a></li>
                    <li><a href="" target="target">Session马上销毁</a></li>
                </ul>
            </li>
            <li><a href="" target="target">浏览器和Session绑定的原理</a></li>
        </ul>
    </div>
</body>
</html>

结果

首次点击

之后点击



k)Session 域数据的存取

修改 SessionServlet

package com.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionServlet extends BaseServlet{
    protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建和获取Session会话对象
        HttpSession session = req.getSession();
        //判断 当前session回滚,是否是新创建出来的
        boolean isNew = session.isNew();
        //获取session会话的唯一标识 id
        String id = session.getId();
        resp.getWriter().write("得到的Session,它的id是:"+id+"<br/>");
        resp.getWriter().write("这个Session是否是新创建的:"+isNew+"<br/>");
    }
    /**
     * 在Session中保存数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.getSession().setAttribute("key1","value1");
       resp.getWriter().write("已经往Session中保存了数据");
    }
    /**
     * 获取Session域中的数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object attribute = req.getSession().getAttribute("key1");
        resp.getWriter().write("从Session中获取key1的数据是"+attribute);
    }
}

修改 session.html

<!DocTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//en" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="pragma" content="no-cache" />
    <meta http-equiv="cache-control" content="no-cache"/>
    <meta http-equiv="Expires" content="0" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Session</title>
    <base href="http://localhost:8080/13_cookie_session/">
    <style type="text/css">
        ul li{
            list-style:none;
        }
    </style>
</head>
<body>
    <iframe name="target" width="500" height="500" style="..."></iframe>
    <div style="...">
        <ul>
            <li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)</a></li>
            <li><a href="sessionServlet?action=setAttribute" target="target">session域数据的存储</a></li>
            <li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a></li>
            <li>session的存活</li>
            <li>
                <ul>
                    <li><a href="" target="target">Session的默认超时及配置</a></li>
                    <li><a href="" target="target">session3秒超时销毁</a></li>
                    <li><a href="" target="target">Session马上销毁</a></li>
                </ul>
            </li>
            <li><a href="" target="target">浏览器和Session绑定的原理</a></li>
        </ul>
    </div>
</body>
</html>

结果



l)Session 生命周期控制

Session的默认超时及配置

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

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

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

public int getMaxInactiveInterval(int interval) 设置Session的超时时间。


public void invalidate() 让当前Session会话马上超时无效。


Session的默认超时时长是多少?

Session的默认超时时长是:1800秒(30分钟)

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

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

修改 session.html

<!DocTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//en" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="pragma" content="no-cache" />
    <meta http-equiv="cache-control" content="no-cache"/>
    <meta http-equiv="Expires" content="0" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Session</title>
    <base href="http://localhost:8080/13_cookie_session/">
    <style type="text/css">
        ul li{
            list-style:none;
        }
    </style>
</head>
<body>
    <iframe name="target" width="500" height="500" style="..."></iframe>
    <div style="...">
        <ul>
            <li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)</a></li>
            <li><a href="sessionServlet?action=setAttribute" target="target">session域数据的存储</a></li>
            <li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a></li>
            <li>session的存活</li>
            <li>
                <ul>
                    <li><a href="sessionServlet?action=defaultLife" target="target">Session的默认超时及配置</a></li>
                    <li><a href="" target="target">session3秒超时销毁</a></li>
                    <li><a href="" target="target">Session马上销毁</a></li>
                </ul>
            </li>
            <li><a href="" target="target">浏览器和Session绑定的原理</a></li>
        </ul>
    </div>
</body>
</html>

修改 SessionServlet

package com.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionServlet extends BaseServlet{
    protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建和获取Session会话对象
        HttpSession session = req.getSession();
        //判断 当前session回滚,是否是新创建出来的
        boolean isNew = session.isNew();
        //获取session会话的唯一标识 id
        String id = session.getId();
        resp.getWriter().write("得到的Session,它的id是:"+id+"<br/>");
        resp.getWriter().write("这个Session是否是新创建的:"+isNew+"<br/>");
    }
    /**
     * 在Session中保存数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.getSession().setAttribute("key1","value1");
       resp.getWriter().write("已经往Session中保存了数据");
    }
    /**
     * 获取Session域中的数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object attribute = req.getSession().getAttribute("key1");
        resp.getWriter().write("从Session中获取key1的数据是"+attribute);
    }
    protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取了Session的默认超时时长
        int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
        resp.getWriter().write("Session的默认超时时长是:"+maxInactiveInterval+"秒");
    }
}

结果



相关文章
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8067 2
|
10天前
|
域名解析 人工智能 Linux
|
21天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
18455 64
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
4天前
|
人工智能 安全 网络安全
|
9天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1496 5
|
8天前
|
云安全 数据采集 人工智能
|
16天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2641 8
|
8天前
|
Web App开发 缓存 安全
巨魔商店 TrollStore 安装教程(2026):免电脑在线安装与全机型安装器矩阵_iOS巨魔安装
巨魔商店(TrollStore)是iOS 14–17.0(特定版本)的永久签名工具,无需越狱,利用CoreTrust漏洞实现IPA签名长期有效,彻底告别7天重签。支持免电脑在线安装(TrollHelperOTA),适配多机型/系统组合,开源免费,安全可控。(239字)
2107 0