javaweb过滤器与监听器

news2024/10/3 4:40:18

一、过滤器程序的基本结构、web.xml文件的配置过程和过滤器的执行过程

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">

    <filter>
        <filter-name>FirstFilter</filter-name>
        <filter-class>filter.FirstFilter</filter-class>
        <init-param>
            <param-name>course</param-name>
            <param-value>Java EE</param-value>
        </init-param>
    </filter>

    <!-- 配置FirstFilter只拦截test.html  -->
    <filter-mapping>
        <filter-name>FirstFilter</filter-name>
        <url-pattern>/test.html</url-pattern>
    </filter-mapping>

</web-app>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Title</title>
</head>
<body>
    这是一个测试过滤器
</body>
</html>
package filter;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

public class FirstFilter implements Filter { //实现Filter接口

    FilterConfig config = null;//定义一个FilterConfig对象为类的实例变量

    public void init(FilterConfig filterConfig) throws ServletException {
        config = filterConfig;//获取FilterConfig对象引用
    }

    public void destroy() {
        config = null;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        String str = config.getInitParameter("course");//获取过滤器初始参数

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<font color=blue>前置程序块<br>");
        out.println("过滤器初始参数:course=" + str + "</font><br><br>");

        chain.doFilter(request, response);//调用"过滤器链"方法

        out.println("<br><font color=blue>后置程序块</font><br>");
    }
}

 过滤器需要实现Filter接口,并重写Filter的三个方法:init()、destory()、doFilter()

过滤器的执行顺序:多个过滤器的拦截路径相同时,首先按照<filter-mapping>标记在web.xml中出现的先后顺序执行过滤器,然后按照过滤器类名的字典顺序执行注解的过滤器。

二、注解配置过滤器:字符编码过滤器及权限验证过滤器的实现

package filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;

import java.io.IOException;

@WebFilter(filterName = "EncodingFilter", urlPatterns = "/*",
        initParams = {@WebInitParam(name = "encode", value = "UTF-8")})
public class EncodingFilter implements Filter {
    private String encode = null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encode = filterConfig.getInitParameter("encode");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding(encode);
        servletResponse.setContentType("text/html;charset="+encode);
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
package filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter(filterName = "ValidationFilter", value = "/admin/*")
public class ValidationFilter implements Filter {
    @Override
    public void init(FilterConfig Config) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpSession session = ((HttpServletRequest) request).getSession();
        if(session.getAttribute("user") == null){
            ((HttpServletResponse) response).sendRedirect("login.jsp");
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
<form action="loginServlet">
	<div id="table_div">
		<table align="center">
		    <tr>
				<td colspan="2"><h2>学生信息管理系统</h2></td>
			</tr>
			<tr>
				<td>账号:</td>
				<td><input class="inputinfo" type="text" name="account" placeholder="账号" /></td>
			</tr>
			<tr >
				<td>密码:</td>
				<td><input class="inputinfo" type="password" name="password" placeholder="密码" /></td>
			</tr>
			<tr>
				<td colspan="2"><input id="btn_submit" type="submit" value="登录" /></td>
			</tr>
		</table>
		</div>
	</form>
package servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		if (account.equals("Sarah") && password.equals("123456")) {
			request.getSession().setAttribute("user", account);
			response.sendRedirect("admin/showAllBooks");
		} else {
			response.sendRedirect("login.jsp");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

三、application、session两类对象的创建与销毁时间监听

package listener;

import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.ServletRequestListener;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
//添加监听器注解
@WebListener
//由MyListener类实现ServletContext、HttpSession、ServletRequest三类对象创建、销毁事件的监听
public class MyListener implements ServletContextListener, HttpSessionListener, ServletRequestListener {
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("\n ServletContext对象被创建了");
    }

    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("\n ServletContext对象被销毁了");
    }

    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("\n HttpSession对象被创建了");
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("\n HttpSession对象被销毁了");
    }

    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("\n servletRequest对象被销毁了");
    }

    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("\n servletRequest对象被创建了");
    }

}

package servlet;


import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;

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

        HttpSession session = request.getSession();//得到会话:如果没有会话,就创建一个

        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet事件监听</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h2>创建了一个会话!</h2>");
        out.println("</body>");
        out.println("</html>");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
<html>
	<head>
		<title>servlet事件监听器</title>
	</head>
	<body>
		<h2>
			用html文档测试servlet事件监听器
		</h2>
	</body>
</html>

(1)启动Tomcat服务器(如果Tomcat已启动,请先关闭),观察控制台输出的信息。这说明了什么?

答:服务器启动时执行contextInitialized(ServletContextEvent sce)方法。首先servletContext全局对象被创建

(2)打开浏览器,输入http://127.0.0.1:8080/lab6_3/index.html网址,观察控制台输出的信息。这又说明了什么?

答:执行requestInitialized(ServletRequestEvent sre)方法,servletRequest对象被创建,随后自动执行requestDestory(ServletRequestEvent sre)方法,servletRequest对象被销毁了

(3)打开浏览器,输入http://127.0.0.1:8080/lab6_3/test网址,观察控制台输出的信息。这又说明了什么?

答:执行requestInitialized(ServletRequestEvent sre)方法,servletRequest对象被创建,紧接着执行了sessionCreated(HttpSessionEvent se)方法,HttpSession对象被创建,最后自动执行requestDestroyed(ServletRequestEvent sre)方法,servletRequest对象被销毁

问题:web.xml中的如下标记实现什么功能?

    <session-config>

        <session-timeout>1</session-timeout>

    </session-config>

(4)过1分钟之后,再次观察控制台输出的信息。这又说明了什么?

答:实现了1分钟后执行sessionDestoryed(HttpSessionEvent se)方法

请总结applicationsession两类对象创建、销毁事件监听的方法与步骤。注意:不同监听接口、事件、方法的差异。

答:首先要实现ServletContextListener、HttpSessionListener、ServletRequestListener。重写三类对象创建和销毁的事件以便监听。当触发相应的Servlet对象就可以实现相应的监听。

  • ServletContextListener:监听application的产生与销毁
  • HttpSessionListener:监听session的产生与销毁
  • ServletRequestListener:监听request的产生与销毁

四、application、session两类对象属性变化事件监听

package listener;
import jakarta.servlet.*;
import jakarta.servlet.http.*;

//由MySttributeListener类实现application、session两类对象属性变化事件的监听
public class MyAttributeListener implements ServletContextAttributeListener, HttpSessionAttributeListener {
    public void attributeAdded(ServletContextAttributeEvent scae) {
        System.out.println("\n application对象中增加了一个名为" + scae.getName()
                + "的属性,该属性值为" + scae.getValue());
    }

    public void attributeRemoved(ServletContextAttributeEvent scae) {
        System.out.println("\n application对象中的" + scae.getName() + "属性被删除了\n");
    }

    public void attributeReplaced(ServletContextAttributeEvent scae) {
        System.out.println("\n application对象中" + scae.getName() + "的属性值被替换成了"
                + scae.getServletContext().getAttribute(scae.getName()));
    }

    public void attributeAdded(HttpSessionBindingEvent hbe) {
        System.out.println("\n session对象中增加了一个名为" + hbe.getName()
                + "的属性,该属性值为" + hbe.getValue());
    }

    public void attributeRemoved(HttpSessionBindingEvent hbe) {
        System.out.println("\n session对象中的" + hbe.getName() + "属性被删除了\n");
    }

    public void attributeReplaced(HttpSessionBindingEvent hbe) {
        System.out.println("\n session对象中" + hbe.getName() + "的属性值被替换成了"
                + hbe.getSession().getAttribute(hbe.getName()));
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">

<!--    <session-config>-->
<!--        <session-timeout>1</session-timeout>-->
<!--    </session-config>-->

    <!-- 把MyAttributeListener类设置事件为监听器 -->
    <listener>
        <listener-class>listener.MyAttributeListener</listener-class>
    </listener>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>
<html>
	<head>
		<title>测试session对象属性变化</title>
	</head>
	<body>
		<%@ page contentType="text/html;charset=gb2312"%>
		<H4>
			这是一个测试session对象属性变化的页面
		</H4>
		<%
			session.setAttribute("width", "98.7654");
			session.setAttribute("width", "9876.54");
			session.removeAttribute("width");
		%>
	</body>
</html>
<html>
	<head>
		<title>测试application对象属性变化</title>
	</head>
	<body>
		<%@ page contentType="text/html;charset=gb2312"%>
		<H4>
			这是一个测试application对象属性变化的页面
		</H4>
		<%
			application.setAttribute("length", "123.45");
			application.setAttribute("length", "1234.5");
			application.removeAttribute("length");
		%>
	</body>
</html>

applicationsession两种事件对象的getName()getValue()的功能是什么?如何获得变化过的属性值?

答:getName()获取application或session的属性名;getValue()获取application或session的属性值。

application对象获得变化过的属性值:getServletContext().getAttribute(getName())

session对象获得变化过的属性值:getSession().getAttribute(getName());

(1)打开浏览器,输入http://127.0.0.1:8080/lab6_4/ServletContextAttributeTest.jsp网址,观察控制台输出的信息。这说明了什么? 

答:application对象设置属性时调用attributeAdded(ServletContextAttributeEvent scae)方法,重新更改属性时调用attributeReplaced(ServletContextAttributeEvent scae)方法,删除属性时调用attributeRemoved(ServletContextAttributeEvent scae)方法

(2)在浏览器输入http://127.0.0.1:8080/lab6_4/HttpSessionAttributeTest.jsp网址,观察控制台输出的信息。这又说明了什么?

答:session对象设置属性时调用attributeAdded(HttpSessionBindingEvent hbe)方法,重新更改属性时调用attributeReplaced(HttpSessionBindingEvent hbe)方法,删除属性时调用attributeRemoved(HttpSessionBindingEvent hbe)方法

请总结applicationsession两类对象属性变化事件监听的方法与步骤。注意:不同监听接口、事件差异,在方法名上有什么相似之处?

答:session对象和application对象都是设置属性时调用attributeAdded()方法,重新更改属性时调用attributeReplaced()方法,删除属性时调用attributeRemoved()方法。

ServletContextAttributeListener和HttpSessionAttributeListener包含的方法名称相同,只是参数不同。

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

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

相关文章

MobPush创建推送

功能说明 MobPush提供遵循REST规范的HTTP接口&#xff0c;适用各开发语言环境调用。 IP绑定 工作台可以绑定服务器IP地址&#xff0c;未绑定之前所有IP均可进行REST API的调用&#xff0c;绑定后进仅绑定的IP才有调用权限。 调用地址 POSThttp://api.push.mob.com/v3/push/c…

03.vue3的计算属性

文章目录1.计算属性1.get()和set()2.computed的简写3.computed和methods对比2.相关demo1.全选和反选2.todos列表1.计算属性 模板内的表达式非常便利&#xff0c;但是设计它们的初衷是用于简单运算的。在模板中放入太多的逻辑会让模板过重且难以维护。所以&#xff0c;对于任何…

CRM系统是什么?它有什么作用?

CRM系统是什么&#xff1f; CRM是Customer Relationship Management&#xff08;客户关系管理&#xff09;的缩写&#xff0c;是一种通过对客户进行跟踪、分析和管理的方法&#xff0c;以增加企业与客户之间的互动和联系&#xff0c;提高企业与客户之间的互信&#xff0c;从而…

GoNote第一章 环境搭建

GoNote第一章 环境搭建 golang介绍 1. 语言介绍 Go 是一个开源的编程语言&#xff0c;它能让构造简单、可靠且高效的软件变得容易。 Go是从2007年末由Robert Griesemer, Rob Pike, Ken Thompson主持开发&#xff0c;后来还加入了Ian Lance Taylor, Russ Cox等人&#xff0c…

oracle远程克隆pdb

使用远程克隆的先决条件是: oracle版本是12.2以上,开启归档模式以及本地undo. 这里是想从172.16.12.250将PRODPDB1克隆到172.16.12.251下&#xff0c;命名为PRODPDB1COPY。 1 确保源端数据库开启归档模式 备注&#xff1a;进cdb里开启归档。 2 在源数据库中&#xff0c;确保…

2023年环境工程与生物技术国际会议(CoEEB 2023)

会议简介 Brief Introduction 2023年环境工程与生物技术国际会议(CoEEB 2023) 会议时间&#xff1a;2023年5月19日-21日 召开地点&#xff1a;瑞典马尔默 大会官网&#xff1a;www.coeeb.org 2023年环境工程与生物技术国际会议(CoEEB 2023)将围绕“环境工程与生物技术”的最新研…

【教程】Unity 与 Simence PLC 联动通讯

开发平台&#xff1a;Unity 2021 依赖DLL&#xff1a;S7.NET 编程语言&#xff1a;CSharp 6.0 以上   一、前言 Unity 涉及应用行业广泛。在工业方向有着一定方向的涉足与深入。除构建数据看板等内容&#xff0c;也会有模拟物理设备进行虚拟孪生的需求需要解决。而 SIMATIC&a…

测评:腾讯云轻量4核8G12M服务器CPU内存带宽流量

腾讯云轻量4核8G12M应用服务器带宽&#xff0c;12M公网带宽下载速度峰值可达1536KB/秒&#xff0c;折合1.5M/s&#xff0c;每月2000GB月流量&#xff0c;折合每天66GB&#xff0c;系统盘为180GB SSD盘&#xff0c;地域节点可选上海、广州或北京&#xff0c;4核8G服务器网来详细…

02-参数传递+统一响应结果

1. 参数传递&#xff1a; -- 简单参数 如果方法形参数名称与请求方法名称不匹配&#xff0c;采用RequestParam注解 -- 实体参数 -- 数组集合参数 -- 日期参数 -- JSON参数 -- 路径参数 2. 统一响应结果 -- 1. 创建Result类&#xff08;放到pojo包中&#xff09; package dem…

centos8 源码安装 apache(内附图片超详细)

♥️作者&#xff1a;小刘在C站 ♥️个人主页&#xff1a;小刘主页 ♥️每天分享云计算网络运维课堂笔记&#xff0c;努力不一定有收获&#xff0c;但一定会有收获加油&#xff01;一起努力&#xff0c;共赴美好人生&#xff01; ♥️夕阳下&#xff0c;是最美的绽放&#xff0…

Redis 如何实现库存扣减操作和防止被超卖?

本文已经收录到Github仓库&#xff0c;该仓库包含计算机基础、Java基础、多线程、JVM、数据库、Redis、Spring、Mybatis、SpringMVC、SpringBoot、分布式、微服务、设计模式、架构、校招社招分享等核心知识点&#xff0c;欢迎star~ Github地址&#xff1a;https://github.com/…

《Rank-LIME: Local Model-Agnostic Feature Attribution for Learning to Rank》论文精读

文章目录一、论文信息摘要二、要解决的问题现有工作存在的问题论文给出的方法&#xff08;Rank-LIME&#xff09;介绍贡献三、前置知识LIMEFeature AttributionModel-AgnosticLocalLearning to Rank&#xff08;LTR&#xff09;单文档方法&#xff08;PointWise Approach&#…

工业相机标定(张正友标定法)

目录 相机标定的概念 a. 相机标定的定义 b. 相机标定的目的 相机标定的过程 a. 标定板选择 b. 标定板摆放及拍摄 c. 标定板角点提取 张正友标定法 a. 反解相机矩阵 b.反解畸变系数 使用Python进行相机标定 a. 安装OpenCV b. 准备标定板图片 c. 利用OpenCV进行角点…

HashMap、HashTable、ConcurrentHashMap 之间的区别

哈喽&#xff0c;大家好~我是保护小周ღ&#xff0c;本期为大家带来的是 HashMap、HashTable、ConcurrentHashMap 之间的区别&#xff0c;从数据结构到多线程安全~确定不来看看嘛~更多精彩敬请期待&#xff1a;保护小周ღ *★,*:.☆(&#xffe3;▽&#xffe3;)/$:*.★* ‘一、…

内存、CPU与指针的知识

在计算机中&#xff0c;内存、CPU和指针是非常重要的概念。在本篇博客中&#xff0c;我们将探讨内存、CPU和指针的知识。 内存的概念 内存是计算机中的一种存储设备&#xff0c;用于存储程序和数据。内存可以被CPU读取和写入&#xff0c;因此是计算机中非常重要的组成部分。在…

006:Mapbox GL添加zoom和旋转控件

第006个 点击查看专栏目录 本示例的目的是介绍演示如何在vue+mapbox中添加zoom和旋转rotation控件 直接复制下面的 vue+mapbox源代码,操作2分钟即可运行实现效果 文章目录 示例效果配置方式示例源代码(共60行)相关API参考:专栏目标示例效果 配置方式 1)查看基础设置:h…

【数据结构第八章】- 排序(万字详解排序算法并用 C 语言实现)

目录 一、基本概念和排序方法概述 1.1 - 排序的基本概念 1.2 - 内部排序的分类 二、插入排序 2.1 - 直接插入排序 2.2 - 希尔排序 三、交换排序 3.1 - 冒泡排序 3.2 - 快速排序 3.2.1 - 递归算法 3.2.2 - 优化 3.2.3 - 非递归算法 四、选择排序 4.1 - 简单选择排…

关于统信UOS(Linux)系统磁盘无损扩容的方法

前言 针对某托管平台分配的4台虚拟服务器&#xff0c;操作系统统信UOS&#xff08;Linux&#xff09;&#xff0c;数据磁盘空间已满&#xff0c;无损扩容的办法。 &#xff08;在操作硬盘扩容前&#xff0c;为了安全起见&#xff0c;请通过磁盘快照功能备份服务器系统盘与数据盘…

Java 堆外内存

文章目录Java 堆外内存堆外内存的分配方式使用 Unsafe 类进行分配使用 ByteBuffer 进行分配堆外内存的查看方式Java 堆外内存 在 Java 虚拟机中&#xff0c;分配对象基本上都是在堆上进行的&#xff0c;然而在有些情况下&#xff0c;缓存的数据量非常大时&#xff0c;使用磁盘或…

【Python_Scrapy学习笔记(十四)】基于Scrapy框架的文件管道实现文件抓取(基于Scrapy框架实现多级页面的抓取)

基于Scrapy框架的文件管道实现文件抓取(基于Scrapy框架实现多级页面的抓取) 前言 本文中介绍 如何基于 Scrapy 框架的文件管道实现文件抓取(基于Scrapy框架实现多级页面的抓取)&#xff0c;并以抓取 第一PPT 网站的 PPT 模板为例进行展示&#xff0c;同时抓取此网站数据的方式…