实验六~Web事件处理与过滤器

news2024/10/6 4:03:55

1. 创建一个名为exp06的Web项目,编写、部署、测试一个ServletContext事件监听器。

 

BookBean代码

package org.example.beans;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2023—04—29
 * Time: 18:39
 */
@SuppressWarnings("serial")
public class BookBean implements Serializable {
    private String bookId;
    private String title;
    private String author;
    private String publisher;
    private double price;

    public String getBookId() {
        return bookId;
    }

    public void setBookId(String bookId) {
        this.bookId = bookId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

BookDao代码 

package org.example.dao;

import org.example.beans.BookBean;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2023—04—29
 * Time: 18:41
 */
public class BookDao {
    private static Connection c;
    public BookDao() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/web_test";
            c = DriverManager.getConnection(url, "root", "142516");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public List<BookBean> getBooks() {
        try {
            String sql = "select * from books";
            PreparedStatement ps = c.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            List<BookBean> books = new ArrayList<>();
            while (rs.next()) {
                BookBean b = new BookBean();
                b.setBookId(rs.getString("book_id"));
                b.setAuthor(rs.getString("author"));
                b.setTitle(rs.getString("title"));
                b.setPublisher(rs.getString("publisher"));
                b.setPrice(rs.getDouble("price"));
                books.add(b);
            }
            return books;
        } catch (Exception e) {
            throw new RuntimeException("查询数据库出错", e);
        }
    }
}

【步骤1】编写监听器类MyServletContextListener.java,Web应用程序启动时创建一个数据源对象,并将其保存在ServletContext作用域中,Web应用销毁时将其清除;在ServletContext对象上添加属性、删除属性和替换属性时,在Tomcat日志中记录有关信息,包括提示信息、属性名和属性值等。

MyServletContextListener.java

package org.example.config;

import javax.servlet.*;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2023—04—26
 * Time: 22:40
 */
public class MyServletContextListener implements ServletContextListener, ServletContextAttributeListener {
    private ServletContext context = null;
    @Override
    public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
        context = servletContextAttributeEvent.getServletContext();
        context.log("添加属性: " + servletContextAttributeEvent.getName()
                    + ": " + servletContextAttributeEvent.getValue());
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
        context = servletContextAttributeEvent.getServletContext();
        context.log("删除属性: " + servletContextAttributeEvent.getName()
                + ": " + servletContextAttributeEvent.getValue());
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
        context = servletContextAttributeEvent.getServletContext();
        context.log("替换属性: " + servletContextAttributeEvent.getName()
                + ": " + servletContextAttributeEvent.getValue());
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        context = servletContextEvent.getServletContext();
        context.log("应用程序已启动: " + new Date());
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        context = servletContextEvent.getServletContext();
        context.log("应用程序已销毁: " + new Date());
    }
}

【步骤2】在web.xml文件中注册监听器类。

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <listener>
        <listener-class>org.example.config.MyServletContextListener</listener-class>
    </listener>
</web-app>

【步骤3】编写监听器测试页面:contextListenerTest.jsp:使用监听器创建的数据源对象连接是一次实验创建的MySQL数据库test,以表格的形式显示其中books数据表的所有内容。

contextListenerTest.jsp

<%@ page import="java.util.*" %>
<%@ page import="org.example.beans.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="book" class="org.example.dao.BookDao" scope="session" />
<html>
<head>
    <title>contextListenerTest</title>
</head>

<body>
    <table width="500" height="256" border="1">
        <tr>
        <th scope="col">bookid</th>
        <th scope="col">title</th>
        <th scope="col">author</th>
        <th scope="col">publisher</th>
        <th scope="col">price</th>
    </tr>
    <%
        List<BookBean> bookList = book.getBooks();
        for (BookBean books : bookList) {
            String book_id = books.getBookId();
            String title = books.getTitle();
            String author = books.getAuthor();
            String publisher = books.getPublisher();
            double price = books.getPrice();
            %>
            <tr>
                <td><%=book_id%> </td>
                <td><%=title%></td>
                <td><%=author%></td>
                <td><%=publisher%></td>
                <td><%=price%></td>
            </tr>
        <% } %>
    </table>
</body>
</html>

 【步骤5】检查日志文件

打开<CATALINA_HOME>\logs目录中的localhost.yyyy-mm-dd.log日志文件,查看执行事件监听器后写到日志文件中的信息。

 2. 编写一个HttpSession事件监听器用来记录当前在线人数。

首先创建一个SessionBean类,用来记录sessionID和注册时间

 

package org.example.beans;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2023—04—29
 * Time: 22:17
 */
@SuppressWarnings("serial")
public class SessionBean implements Serializable {
    private String id;
    private String creationTime;

    public SessionBean(String id, String creationTime) {
        this.id = id;
        this.creationTime = creationTime;
    }
    public SessionBean() {}

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCreationTime() {
        return creationTime;
    }

    public void setCreationTime(String creationTime) {
        this.creationTime = creationTime;
    }
}

 

【步骤1】编写MySessionListener监听器处理类,监视Web应用会话创建事件:每创建一个新的会话对象,就将其保存到会话对象的列表数组中,并将用户会话对象列表保存在ServletContext作用域中的sessionList属性中,同时向日志中写入“创建一个新会话”以及该会话的ID。当一个会话对象被删除时,从用户会话对象列表中删除该会话对象并保存,同时向日志中写入“删除一个会话”以及该会话的ID。

package org.example.config;

import org.example.beans.SessionBean;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2023—04—29
 * Time: 21:59
 */
public class MySessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        ServletContext application = httpSessionEvent.getSession().getServletContext();
        List<SessionBean> sessionList = (List<SessionBean>)application.getAttribute("sessionList");
        if (sessionList == null) {
            sessionList = new ArrayList<>();
            application.setAttribute("sessionList", sessionList);
        }
        long time = httpSessionEvent.getSession().getCreationTime();
        Date date = new Date(time);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String creationTime = sd.format(date);
        SessionBean sessionBean = new SessionBean(httpSessionEvent.getSession().getId(),
                creationTime);
        sessionList.add(sessionBean);
        application.log("创建一个新会话,其id为: " + httpSessionEvent.getSession().getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext application = httpSessionEvent.getSession().getServletContext();
        List<SessionBean> sessionList = (List<SessionBean>)application.getAttribute("sessionList");
        String sessionId = httpSessionEvent.getSession().getId();
        for(SessionBean session : sessionList) {
            if (session.getId().equals(sessionId)) {
                sessionList.remove(session);
            }
        }
        application.log("删除一个新会话,其id为: " + sessionId);
        application.setAttribute("sessionList", sessionList);
    }
}

【步骤2】在web.xml文件中注册该事件监听器。

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <listener>
        <listener-class>org.example.config.MyServletContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.example.config.MySessionListener</listener-class>
    </listener>
</web-app>

【步骤3】编写一个测试该监听器的页面sessionDisplay.jsp,显示当前应用所有在线的会话对象的id及创建时间。多打开几个浏览器窗口,模拟多用户访问,查看多用户会话统计出的结果。

<%@ page import="java.util.*" %>
<%@ page import="org.example.beans.*" %>
<%@ page contentType="text/html;charset=utf-8" %>
<html>
<head>
    <title>sessionDisplay</title>
<style>
    td{
        text-align: center;
    }
</style>
</head>
<body>
    <table width="500" height="256" border="1">
        <tr>
        <th scope="col">会话id</th>
        <th scope="col">创建时间</th>
    </tr>
    <%
        ServletContext context = getServletConfig().getServletContext();
        List<SessionBean> sessionList = (List<SessionBean>) context.getAttribute("sessionList");
        for (SessionBean s : sessionList) {
            String id = s.getId();
            String creationTime = s.getCreationTime();
            %>
            <tr>
                <td><%=id%> </td>
                <td><%=creationTime%></td>
            </tr>
        <% } %>
    </table>
</body>
</html>

 

3. 编写一个ServletRequestListener监听器,记录某个页面自应用程序启动以来被访问的次数。 

 【步骤1】编写监听器接口MyRequestListener,在对指定页面onlineCount.jsp发送请求时进行该页面访问次数计数器累加,并将计数器变量保存到应用作用域的属性中。

package org.example.config;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2023—04—30
 * Time: 0:04
 */
public class MyRequestListener implements ServletRequestListener {
    private int count = 0;
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
    }

    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        HttpServletRequest request1 = (HttpServletRequest) servletRequestEvent.getServletRequest();
        if(request1.getRequestURI().equals("/exp06/onlineCount.jsp")){
            count++;
            servletRequestEvent.getServletContext().setAttribute("count",new Integer(count));
        }
    }
}

【步骤2】在web.xml文件中注册该监听器。

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <listener>
        <listener-class>org.example.config.MyServletContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.example.config.MySessionListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.example.config.MyRequestListener</listener-class>
    </listener>
</web-app>

【步骤3】编写一个JSP页面onlineCount.jsp。

<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head><title>Listener test</title>
</head>
<body>
欢迎您,您的IP地址是<%= request.getRemoteAddr() %>
<p>自应用程序启动以来,该页面被访问了
<font color="blue" ><%=application.getAttribute("count")%>
</font>次<br>
</body>
</html>

【步骤4】启动多个浏览器窗口访问该jsp页面,展示并分析程序的运行结果。

 

 

 

 

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

DDD系列:二、应用架构设计演变

作用: ​ 通过规定一个固定的架构设计&#xff0c;可以让团队内有一个统一的开发规范&#xff0c;降低沟通成本&#xff0c;提升效率和代码质量。 目标&#xff1a; ​ 在做架构设计时&#xff0c;一个好的架构应该需要实现以下几个目标&#xff1a; 独立于UI&#xff1a;前…

02-Vue技术栈之基础篇(下)

目录 1、class 与 style 绑定1.1 理解1.2 class 绑定1.3 style绑定1.4 代码示例 2、条件渲染2.1 v-if2.2 v-show2.3 注意事项2.4 代码示例 3、列表渲染3.1 基本列表3.2 key的原理3.2.1 虚拟DOM中key的作用&#xff1a;3.2.2 对比规则&#xff1a;3.2.3 用index作为key可能会引发…

防火墙GRE和NAT

要求&#xff1a; Pc2和pc3之间互通&#xff1b;做gre pc2与pc3访问公网pc1要做地址转换 基本配置&#xff1a;省略&#xff0c;小孩子都会 这里查看效果&#xff1a; 区域划分 fw1&#xff1a; fw2&#xff1a; 接口地址划分&#xff1a; fw1&#xff1a; fw2&#xff1a;…

武汉大学惯性导航课程合集【2021年秋】1.1惯性导航和惯性器件

重力外力加速度 机械阻尼换为电阻尼&#xff0c;带宽提高取决于控制器响应速度 右方是不平衡跷跷板&#xff0c;测量顶面电容 机械中测量角速度的旋转编码器&#xff0c;测速电机测量的两个看得见实际物体的转子定子相对角速度&#xff0c;但是陀螺是相对于惯性参考系&#xf…

【YOLO系列】YOLOv6论文超详细解读(翻译 +学习笔记)

前言 YOLOv6 是美团视觉智能部研发的一款目标检测框架&#xff0c;致力于工业应用。论文题目是《YOLOv6: A Single-Stage Object Detection Framework for Industrial Applications》。 本框架同时专注于检测的精度和推理效率&#xff0c;在工业界常用的尺寸模型中&#xff…

如何让 Edge 浏览器更干净!

如果你也喜欢 Edge 或想要尝试迁移&#xff0c;本文介绍一些能够让 Edge 浏览器体验更加干净、纯粹的设置技巧。 洗白新标签页 Edge 的新标签页提供了多种页面设置方案&#xff0c;在没有安装第三方新标签页扩展的前提下&#xff0c;我们可以在默认新标签页右上角的齿轮设置中…

【MCS-51】时钟电路和复位

单片机的处理器内部具有众多模块&#xff0c;但是要想协调这些模块统一工作并不是一件易事。为了确保各部分能够统一有序工作&#xff0c;因为单片机已经是一个同步时序电路&#xff0c;所以要想让它内部能够有序工作&#xff0c;我们需要从外部输入一个时钟信号。 目录 &am…

MyBatis凭什么征服SpringBoot ?

1、MyBatis的优势 众所周知&#xff0c;MyBatis 是一款优秀的持久层框架&#xff0c;它支持自定义 SQL、存储过程以及高级映射。通过xml映射到接口&#xff0c;使开发者使用接口的方式就能够轻松的映射、解析、执行xml中的SQL。MyBatis 消除了几乎所有的JDBC代码和参数的手工设…

No.052<软考>《(高项)备考大全》【冲刺6】《软考之 119个工具 (4)》

《软考之 119个工具 &#xff08;4&#xff09;》 61.人际交往:62.组织理论:63.预分派:64.谈判:65.招募:66.虚拟团队:67.多标准决策分析:68.人际关系技能:69.培训:70.团队建设活动:71.基本规则:72.集中办公:73.认可与奖励:74.人事评测工具:75.观察和交谈:76.项目绩效评估:77.冲…

Linux学习[8]查找文件指令:which whereis locate find

文章目录 前言1. which2. whereis3. locate4. find总结&#xff1a; 前言 之前在弄交叉编译的时候需要找到gcc&#xff0c;gdb什么的在哪里&#xff1b;涉及到了查找文件指令。 这里对linux中的查找指令进行总结 1. which which指令一般用来寻找可执行文件的路径&#xff0c;…

OpenCV实战(20)——图像投影关系

OpenCV实战&#xff08;20&#xff09;——图像投影关系 0. 前言1. 相机成像原理2. 图像对的基本矩阵3. 完整代码小结系列链接 0. 前言 数码相机通过将光线通过镜头投射到图像传感器上来捕捉场景产生图像。由于通过将 3D 场景投影到 2D 平面上形成图像&#xff0c;因此场景与其…

时序预测 | MATLAB实现BO-CNN-GRU贝叶斯优化卷积门控循环单元时间序列预测

时序预测 | MATLAB实现BO-CNN-GRU贝叶斯优化卷积门控循环单元时间序列预测 目录 时序预测 | MATLAB实现BO-CNN-GRU贝叶斯优化卷积门控循环单元时间序列预测效果一览基本介绍模型描述程序设计参考资料 效果一览 基本介绍 基于贝叶斯(bayes)优化卷积神经网络-门控循环单元(CNN-GR…

2023年人工智能GPT-4时代,最新13个ChatGPT商业市场AIGC应用正在掀起革命性变革!

目录 前言ChatGPT商业应用——LLM是星辰大海1. 研究背景1.1 研究背景1.2 研究方法 2. 商业应用和案例分析2.1 工具层ChatGPT搜索ChatGPT办公ChatGPT教育 2.2 行业层ChatGPT游戏ChatGPT音乐ChatGPT零售电商ChatGPT广告营销ChatGPT媒体新闻ChatGPT金融ChatGPT医疗ChatGPT设计Chat…

AI绘画能力的起源:通俗理解VAE、扩散模型DDPM、ViT/Swin transformer

前言 2018年我写过一篇博客&#xff0c;叫&#xff1a;《一文读懂目标检测&#xff1a;R-CNN、Fast R-CNN、Faster R-CNN、YOLO、SSD》&#xff0c;该文相当于梳理了2019年之前CV领域的典型视觉模型&#xff0c;比如 2014 R-CNN2015 Fast R-CNN、Faster R-CNN2016 YOLO、SSD2…

Linux命令集(Linux网络连接管理命令--ifconfig指令篇)

Linux命令集&#xff08;Linux网络连接管理命令--ifconfig指令篇&#xff09; Linux网络连接管理命令集&#xff08;ifconfig指令篇&#xff09;1. ifconfig(interface configuration)1. 信息显示2. 接口配置 Linux网络连接管理命令集&#xff08;ifconfig指令篇&#xff09; 如…

C++Primer第五版【阅读笔记】

CPrimer第五版 阅读笔记 第1章开始1.1 编写一个简单的C程序1.1.1 编译、运行程序 1.2 初识输入输出1.3 注释简介1.4 控制流1.4.1 while语句1.4.2 for语句1.4.3 读取数量不定的输入数据1.4.4 if语句 1.5 类简介1.5.1 Sales_item 类1.5.2 初识成员函数 1.6 书店程序第一章小结 第…

【Linux入门】linux指令(1)

【Linux入门】linux指令&#xff08;1&#xff09; 目录 【Linux入门】linux指令&#xff08;1&#xff09;操作系统登录服务器Linux下的基本指令ls指令pwd指令Linux路径分割符 /cd指令touch指令mkdir指令&#xff08;重要&#xff09;rmdir指令&&rm指令&#xff08;重…

4.30下周美联储携非农来袭黄金多空该如何布局?

近期有哪些消息面影响黄金走势&#xff1f;下周黄金多空该如何研判&#xff1f; ​黄金消息面解析&#xff1a;周五(4月28日)当周金价维持震荡交投&#xff0c;金价基本持稳于2000美元下方。支撑和打压金价的因素参半。经济衰退的担忧&#xff0c;以及避险情绪支持金价&#x…

Fabric.js 讲解官方demo:Stickman

theme: smartblue 本文简介 戴尬猴&#xff0c;我是德育处主任 Fabric.js 官网有很多有趣的Demo&#xff0c;不仅可以帮助我们了解其功能&#xff0c;还可以为我们提供创意灵感。其中&#xff0c;Stickman是一个非常有趣的例子。 先看看效果图 从上图可以看出&#xff0c;在拖拽…

【SpringBoot2】二:基础入门---自动配置原理(SpringBoot特点+容器功能)

文章目录 1.SpringBoot特点1.1 依赖管理1.2 自动配置 2.容器功能2.1 组件添加2.1.1Configuration2.1.2 Bean、Component、Controller、Service、Repository2.1.3 ComponentScan、Import2.1.4 Conditional 2.2 原生配置引入ImportResource2.3 配置绑定2.3.1 Component Configur…