servlet-会话(cookie与session)

servlet会话技术

  • 会话技术
  • cookie
  • 创建Cookie
    • index.jsp
    • CookieServlet
  • 获取Cookie
    • index.jsp
    • showCookie
  • session
  • 创建session
    • index.jsp
    • login.jsp
    • LoginServlet
  • 获取session
    • RedurectServket
  • 清除会话
    • login.jsp
    • ClearItmeServlet

会话技术

两种会话:cookie,session

  • 会话:当用户打开浏览器的时候,访问不同的资源( url ),用户将浏览器关闭,可以认为这是一次会话.
  • 作用:http 协议是一个无状态的协议, http 记录不了上次访问平台时间等信息的;用户在访问过程中可能会产生一些数据,所以通过 cookie 会话将常用数据保存起来
    如:用户登录( session 用得最多,信息保存安全),访问记录( cookie 会话使用多,保存信息不关乎安全)
  • 分类:
    cookie:浏览器端会话技术[针对浏览器,安全系数低](记录常用信息,又不影响安全的信息)
    session:服务器端会话技术[针对服务器,安全性高](主要:用户登录)

cookie

cookie 是由服务器生成,通过 response 将 cookie 写回浏览器,保留在浏览器上,下一次访问,浏览器根据一定规则携带不同的 cookie (通过 request 的头 cookie ),服务器就可以接收到对应的cookie【如准考证号,唯一性】。
1).cookie 创建:
new Cookie(String key,String value)
2).写回至浏览器:
response.addCookie(Cookie c)
3).获取 cookie(数组):
Cookie[] request.getCookies()
4).cookie 常用方法:
getName():获取 cookie 的 key(名称)
getValue:获取 cookie 值

创建Cookie

index.jsp

    <a href="<%=request.getContextPath()%>/creatCookie">创建Cookie</a>

CookieServlet

@WebServlet(name = "creatCookie", value = "/creatCookie")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        //创建Cookie
        Cookie id = new Cookie("id", "1");
        Cookie shop = new Cookie("shop", "XIAOMI");
//      如果 cookie 需要写入中文,用 new Cookie("aNameKey", URLEncoder.encode("李","utf-8"));方式
//      如果取 cookie 中文值用 URLDecoder.decode(cookie.getValue(), "UTF-8");
        Cookie shopNmae = new Cookie("shopName", URLEncoder.encode("小米","utf-8"));

        //回显到浏览器
        response.addCookie(id);
        response.addCookie(shop);
        response.addCookie(shopNmae);

        response.getWriter().append("Cookie已创建");
    }

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

在这里插入图片描述

获取Cookie

index.jsp

    <a href="<%=request.getContextPath()%>/creatCookie">创建Cookie</a>
    <br>
    <a href="<%=request.getContextPath()%>/showCookie">获取cookie值</a>

showCookie

@WebServlet(name = "showCookie", value = "/showCookie")
public class ShowCookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
//      如果 cookie 需要写入中文,用 new Cookie("aNameKey", URLEncoder.encode("李","utf-8"));方式
//      如果取 cookie 中文值用 URLDecoder.decode(cookie.getValue(), "UTF-8");
//回显到浏览器
            response.getWriter()
                    .append(cookie.getName() + "==" + URLDecoder.decode(cookie.getValue(),"utf-8"))
                    .append("<br>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

在这里插入图片描述

session

1).服务器( tomcat )端会话技术
2).获取一个session:
HttpSession request.getSession()
3).域对象:
xxxAttribute(setAttribute,getAttribute)
销毁:
a).服务器非正常关闭(突然宕机)
b).session 超时
默认时间超时:30分钟 tomcat 里的 web.xml 有配置
手动设置超时:setMaxInactiveInterval(秒)
c).手动编写清除 session 会话方法:
清除所有:session.invalidate();
清除单个:session.remove(“username”);(掌握)

创建session

index.jsp

    <a href="<%=request.getContextPath()%>/creatCookie">创建Cookie</a>
    <br>
    <a href="<%=request.getContextPath()%>/showCookie">获取cookie值</a>
    <br>
    <a href="login.jsp">登录</a>

login.jsp

  <form action="<%=request.getContextPath()%>/login" method="post">
    <label>用户名:</label><input type="text" name="username">
    <br>
    <label>密码:</label><input type="password" name="password">
    <br>
    <input type="submit" value="登录">
  </form>
  <br>
  <a href="/f_session/cleitme">清空itme会话</a>

LoginServlet

@WebServlet(name = "login", value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取login.jsp传递的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //假定数据库存有两个对象
        List<User> users = new ArrayList<>();
        users.add(new User("zhangsan", "123"));
        users.add(new User("lisi","1234"));

        if(users.size()>0){//判断数据库中是否有数据
            for (User user : users) {//遍历数据库
                if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
                    //创建session
                    HttpSession session = request.getSession();
                    //设置域对象
                    session.setAttribute("usersession", user);
                    response.sendRedirect(request.getContextPath() + "/redu");

                }
            }
        }
    }
}

获取session

RedurectServket

@WebServlet("/redu")
public class RedurectServket extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得session
        HttpSession session = request.getSession();
        //获得域对象数据
        User ussess = (User) session.getAttribute("usersession");
        response.getWriter().append(ussess.getUsername()+",===,"+ussess.getPassword());
        System.out.println("执行方法");
    }

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

在这里插入图片描述
在这里插入图片描述

清除会话

login.jsp

  <form action="<%=request.getContextPath()%>/login" method="post">
    <label>用户名:</label><input type="text" name="username">
    <br>
    <label>密码:</label><input type="password" name="password">
    <br>
    <input type="submit" value="登录">
  </form>
  <br>
  <a href="<%=request.getContextPath()%>/cleitme">清空itme会话</a>

ClearItmeServlet

@WebServlet("/cleitme")
public class ClearItmeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        HttpSession session = request.getSession();

        //session.invalidate()//手动清空所有
        session.removeAttribute("usersession");//工作时使用这样指定方式移除以避免会话全部清空
        response.getWriter().print("usersession此会话已清除");
    }

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

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/602857.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

在 Linux 中创建文件

目录 ⛳️推荐 前言 使用 touch 命令创建一个新的空文件 使用 echo 命令创建一个新文件 使用 cat 命令创建新文件 测试你的知识 ⛳️推荐 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到…

利用Python简单操作MySQL数据库,轻松实现数据读写

PyMySQL是Python编程语言中的一个第三方模块&#xff0c;它可以让Python程序连接到MySQL数据库并进行数据操作。它的使用非常简单&#xff0c;只需要安装PyMySQL模块&#xff0c;然后按照一定的步骤连接到MySQL数据库即 可。本文将介绍PyMySQL的安装、连接MySQL数据库、创建表、…

嗨动PDF编辑器V1.60版本发布,有哪些亮点值得注意!

嗨动PDF编辑器V1.60版发布&#xff0c;有哪些亮点值得注意呢&#xff1f; 在数字信息爆炸的时代&#xff0c;PDF文档以其跨平台、易于阅读和保持格式统一的特性&#xff0c;成为了工作、学习和生活中的常客。但很多时候&#xff0c;我们收到的PDF文档只是“只读”的&#xff0…

什么是香草看涨期权?香草看涨期权有哪些特点?

什么是香草看涨期权&#xff1f;香草看涨期权有哪些特点&#xff1f; 香草看涨期权&#xff0c;通常也称为香草期权&#xff0c;是金融市场上的一种金融衍生品&#xff0c;由券商或金融机构推出。它允许投资者以较小的费用获取相应股票市值的收益权&#xff0c;主要用于风险管…

6款好用的数据恢复软件推荐【不收费】+【收费】

日常办公和学习中&#xff0c;总有一些小粗心鬼会不小心误删了自己的重要文件&#xff0c;或者是由于设备故障导致数据丢失。如果需要进行数据恢复&#xff0c;那么可以试试数据恢复工具&#xff0c;只需要自己再电脑中操作&#xff0c;就可以帮助找回数据文件&#xff0c;下面…

基于随机森林与支持向量机的高光谱图像分类(含python代码)

目录 一、背景 二、代码实现 三、项目代码 一、背景 基于深度学习的教程&#xff08;卷积神经网络&#xff09;详见&#xff1a;基于卷积神经网络的高光谱图像分类详细教程&#xff08;含python代码&#xff09;-CSDN博客 在高光谱图像分类领域&#xff0c;随机森林&#…

CAT Game Builder

CAT游戏生成器是在Unity中制作游戏的更简单、更快的方法。使用CAT的模块化条件、动作、触发器和集成游戏系统,您可以创建原型、演示或完整游戏,而无需额外编程。 CAT Game Builder是一个完全可扩展的框架,专为专业团队设计,但对初学者来说足够容易掌握。CAT Game Builder使…

2024蓝桥杯CTF writeUP--Theorem

密码方向的签到题&#xff0c;根据题目已知n、e和c&#xff0c;并且p和q是相邻的素数&#xff0c;可以考虑分解。 通过prevprime函数分解n&#xff0c;然后 RSA解密即可&#xff1a; from Crypto.Util.number import long_to_bytes import gmpy2 import libnumfrom sympy im…

大语言模型LLM入门篇

大模型席卷全球&#xff0c;彷佛得模型者得天下。对于IT行业来说&#xff0c;以后可能没有各种软件了&#xff0c;只有各种各样的智体&#xff08;Agent&#xff09;调用各种各样的API。在这种大势下&#xff0c;笔者也阅读了很多大模型相关的资料&#xff0c;和很多新手一样&a…

1.数据结构---顺序表

ArrayList 在new的时候并没有进行内存的分配 此时才进行内存分配 两个结论: 第一次Add的时候分配大小为10的内存 扩容是1.5倍扩容

如何修复显示器或笔记本电脑屏幕的黄色色调?这里提供几种方法

序言 如果你的笔记本电脑屏幕呈淡黄色,则可以启用夜灯功能。该问题也可能源于连接松散的显示电缆、损坏的显卡驱动程序或错误配置的显示器设置。以下是一些故障排除步骤,你可以尝试解决此问题。 禁用夜间模式 夜间模式功能旨在减少显示器的蓝色色调,使屏幕看起来更温暖,…

光伏设备数据交互模硬件接口要求

模组的弱电接口采用26&#xff08;间距2.54mm&#xff09;双排插针作为连接件&#xff0c;模组与电能表的硬件接口示意图如 图1所示&#xff08;模组正视图方向&#xff09;&#xff0c;接口定义说明见表3。模组外接插座和插头采用凤凰端子结构&#xff0c;接口示意 图应符合附…

网贷大数据查询要怎么保证准确性?

相信现在不少人都听说过什么是网贷大数据&#xff0c;但还有很多人都会将它跟征信混为一谈&#xff0c;其实两者有本质上的区别&#xff0c;那网贷大数据查询要怎么保证准确性呢?本文将为大家总结几点&#xff0c;感兴趣的朋友不妨去看看。 想要保证网贷大数据查询的准确度&am…

差动绕组电流互感器过电压保护器ACTB

安科瑞薛瑶瑶18701709087/17343930412 电流互感器在运行中如果二次绕组开路或一次绕组流过异常电流&#xff0c;都会在二次侧产生数千伏甚至上万伏的过电压。这不仅会使CT和二次设备损坏&#xff0c;也严重威胁运行人员的生命安全&#xff0c;并造成重大经济损失。采用电流互感…

SpringBoot多数据源配置

&#x1f353; 简介&#xff1a;java系列技术分享(&#x1f449;持续更新中…&#x1f525;) &#x1f353; 初衷:一起学习、一起进步、坚持不懈 &#x1f353; 如果文章内容有误与您的想法不一致,欢迎大家在评论区指正&#x1f64f; &#x1f353; 希望这篇文章对你有所帮助,欢…

Git知识点总结

目录 1、版本控制 1.1什么是版本控制 1.2常见的版本控制工具 1.3版本控制分类 2、集中版本控制 SVN 3、分布式版本控制 Git 2、Git与SVN的主要区别 3、软件下载 安装&#xff1a;无脑下一步即可&#xff01;安装完毕就可以使用了&#xff01; 4、启动Git 4.1常用的Li…

CentOS 7 :虚拟机网络环境配置+ 安装gcc(新手进)

虚拟机安装完centos的系统却发现无法正常联网&#xff0c;咋破&#xff01; 几个简单的步骤&#xff1a; 一、检查和设置虚拟机网络适配器 这里笔者使用的桥接模式&#xff0c;朋友们可以有不同的选项设置 二、查看宿主机的网络 以笔者的为例&#xff0c;宿主机采用wlan上网模…

在python中对Requests的理解

离上次写文章已经有小半个月了&#xff0c;但是&#xff1a; 没有动态的日子里&#xff0c;都在努力生活❤️&#xff1b;发表动态的日子里&#xff0c;都在热爱生活。&#x1f339; 目录 一、python集成工具的分类&#xff1a;1.解释Requests2. Requests3. Response对象的属性…

mvc 异步请求、异步连接、异步表单

》》》 利用Jquery ajax 》》》 mvc 异步表单 c# MVC 添加异步 jquery.unobtrusive-ajax.min.js 方法 具–>Nuget程序包管理器–>程序包管理器控制台 在控制台输入&#xff1a;PM>Install-Package Microsoft.jQuery.Unobtrusive.Ajax –version 3.0.0 回车执行即可在…

5分钟了解Flutter线程Isolate的运用以及Isolate到底是怎样执行的

5分钟了解Flutter线程Isolate的运用以及Isolate到底是什么 Isolate在dart是什么flutter线程内存隔离Isolate的使用第一种&#xff0c;无参数使用Isolate.run 第二种&#xff0c;有参数使用compute:使用Isolate.spawn Isolate与外面线程通讯Isolate以文件形式加载到内存运行 Iso…