JavaWeb三大组件——Listener

news2024/9/21 11:03:29

   

目录

 Listener

八个Web监听器

注册Listener

父pom文件

pom文件

使用注解方式

ServletListener 

 HelloServlet 

 启动类

通过RegistrationBean注册

ServletListener

HelloServlet

MyWebConfig 

启动类

 运行结果


     

 Listener

作用:监听某个事件的发生,状态的改变
内部机制:接口回调

八个Web监听器

接口名作用
ServletContextListenerServletContext对象的创建
HttpSessionListenerSession对象的创建
ServletRequestListenerRequest对象的创建
ServletContextAttributeListenerServletContext属性变化
HttpSessionAttributeListenerSession属性变化
ServletRequestAttributeListenerRequest属性变化
HttpSessionActivationListenerSession钝化与活化
HttpSessionBindingListenerSession与对象的绑定

注册Listener

 

父pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
<!--        <version>3.1.2</version>-->
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.chensir</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot</name>
    <description>springboot</description>
    <properties>
        <java.version>8</java.version>
    </properties>

    <packaging>pom</packaging>

    <modules>
        <module>servlet</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.3</version>
        </dependency>

<!--        <dependency>-->
<!--            <groupId>org.slf4j</groupId>-->
<!--            <artifactId>slf4j-log4j12</artifactId>-->
<!--            <version>1.7.25</version>-->
<!--        </dependency>-->

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.chensir</groupId>
        <artifactId>springboot</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>servlet</artifactId>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

使用注解方式

使用注解 在启动类上必须加 @ServletComponentScan注解,若使用bean方式注册,则不需要

ServletListener 

package com.chensir.javaWeb;

import cn.hutool.core.date.StopWatch;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;

@WebListener
@Slf4j
public class ServletListener implements ServletRequestListener {

    // StopWatch存储一组任务耗时时间
    StopWatch stopWatch = null;

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        stopWatch = new StopWatch("监控");
        stopWatch.start();
        log.info("-------有人来了----------");
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre){
        stopWatch.stop();
        log.info("-------有人出来了,耗时:{}----------",stopWatch.getTotalTimeSeconds());

        // todo:如果超过多少时间,发信息给开发者
    }
}

 HelloServlet 

package com.chensir.javaWeb;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = {"/hello"})
@Slf4j
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write("你好,宝宝");

        log.info("给航天员打招呼!");

        // 睡眠5s
        ThreadUtil.safeSleep(5000);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    }
}

 启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
public class ServletApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServletApplication.class, args);
    }

}

通过RegistrationBean注册

ServletListener

 

HelloServlet

 MyWebConfig 

import com.chensir.javaWeb.HelloServlet;
import com.chensir.javaWeb.ServletListener;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyWebConfig {

    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new HelloServlet());
        servletRegistrationBean.addUrlMappings("/helloBaby");
        return servletRegistrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean() {
        ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean();
        bean.setListener(new ServletListener());
        // 启用
        bean.setEnabled(true);
        return bean;
    }
}

启动类

 运行结果

 

 

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

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

相关文章

区块链实验室(16) - FISCO BCOS实验环境

经过多次重复&#xff0c;建立一个FISCO BCOS实验环境。该环境是一个VMWare虚拟机&#xff0c;能够启动FISCO BCOS自创建的4节点区块链&#xff0c;不必下载依赖包即可编译Fisco Bcos目标文件&#xff0c;安装有VsCode1.81版本。 启动4节点的Fisco Bcos区块链 启动控制台 编译…

CHI(六)独占访问

AMBA5 CHI Architecture Specification IssueF 1. overview 独占访问的原则是&#xff0c;执行独占序列的逻辑处理器&#xff08;LP&#xff09;执行以下操作&#xff1a; 对一个地址执行exclusive load。计算要存储到该位置的新值。对该地址进行exclusive store。 支持对可…

【肺炎分类数据集】数据量非常充足的新冠肺炎分类数据共享

一、肺炎数据集介绍&#x1f349;&#xff1a; 1.1 格式&#x1f388; 按照标准的格式分为了①训练集train&#xff08;134138575198张&#xff09;&#xff0c;②验证集val&#xff08;8816张&#xff09;&#xff0c;③测试集test&#xff08;234390624张&#xff09;&#…

redis入门3-在java中操作redis

Redis的java客户端 Jedis、Lettuce、Redisson、以及spring提供的spring data redis Jedis操作redis //添加依赖 <dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.8.0</version> </dep…

DAY3,C高级(shell中的变量、数组、算术运算、分支结构)

1.今日思维导图&#xff1b; 2.判断家目录下&#xff0c;普通文件的个数和目录文件的个数&#xff1b; 1 #!/bin/bash2 arr1(ls -la ~/ | cut -d r -f 1 | grep -w -)3 arr2(ls -la ~/ | cut -d r -f 1 | grep -w d)4 echo "普通文件个数&#xff1a;${#arr1[*]}"5 e…

SpringCloud深度学习(在更)

微服务简介 微服务是什么&#xff1f; 微服务是一种架构风格&#xff0c;将一个大型应用程序拆分为一组小型、自治的服务。每个服务都运行在自己独立的进程中&#xff0c;使用轻量级的通信机制&#xff08;通常是HTTP或消息队列&#xff09;进行相互之间的通信。这种方式使得…

Tensorrt 原生Activate 算子讲解

Tensorrt operators docs&#xff1a; Activation Apply an activation function on an input tensor A and produce an output tensor B with the same dimensions. import numpy as np from cuda import cudart import tensorrt as trt # 输入张量 NCHW nIn, cIn, hIn, wI…

【每日一题】—— B1. Palindrome Game (easy version)(Codeforces Round 721 (Div. 2))

&#x1f30f;博客主页&#xff1a;PH_modest的博客主页 &#x1f6a9;当前专栏&#xff1a;每日一题 &#x1f48c;其他专栏&#xff1a; &#x1f534; 每日反刍 &#x1f7e1; C跬步积累 &#x1f7e2; C语言跬步积累 &#x1f308;座右铭&#xff1a;广积粮&#xff0c;缓称…

Oracle-expdp报错ORA-39077、06502(Bug-16928674)

问题: 用户在使用expdp进程导出时&#xff0c;出现队列报错ORA-39077、ORA-06502 ORA-31626: job does not exist ORA-31638: cannot attach to job SYS_EXPORT_SCHEMA_01 for user SYS ORA-06512: at "SYS.DBMS_SYS_ERROR", line 95 ORA-06512: at "SYS.KUPV$…

React 核心开发者 Dan Abramov 宣布从 Meta 离职

导读React.js 核心开发者、Redux 作者 Dan Abramov 在社交平台发文宣布&#xff0c;将辞去在 Meta 的职务&#xff1a; “我感到苦乐参半&#xff0c;几周后我就要辞去 Meta 的工作了。在 Meta 的 React 组织工作是我的荣幸。感谢我过去和现在的同事接纳我&#xff0c;容忍我犯…

MySql的Windows安装指南

目录 一、MySQL的4大版本 二、软件的下载 三、MySQL8.0 版本的安装 四、配置MySQL8.0 五、配置MySQL8.0 环境变量 六、登录验证 一、MySQL的4大版本 MySQL Community Server 社区版本&#xff0c;开源免费&#xff0c;自由下载&#xff0c;但不提供官方技术支持&#xff…

RIP Bram Moolenaar

Grateful for your work on Vim and for the impact Vim has had on the world. Thank you for everything, Bram.

原创 | 图神经网络在区块链交易数据分析研究中的应用

作者&#xff1a;王佳鑫本文约3000字&#xff0c;建议阅读6分钟区块链技术带来的重大变革&#xff0c;也对金融服务、生态安全、隐私保护提出了诸多挑战。 加密数字货币是数字货币的一种&#xff0c;它不依靠法定货币机构发行&#xff0c;不受央行管控。借助于区块链等新兴技术…

机器学习中的人生启示:“没有免费的午餐”定理(NFL)的个人发展之道→探讨感觉和身边其他人有差距怎么办?

文章目录 1 引言2 探究NFL定理的含义3 将NFL定理应用于个人发展4 探索个人兴趣和天赋5 结论 1 引言 机器学习中的“没有免费的午餐”定理&#xff08;NFL&#xff09;是一条深具启示意义的原则。该定理表明&#xff0c;没有一种算法可以在所有问题上都表现最好。在机器学习领域…

MyBatis核心 - SqlSession如何通过Mapper接口生成Mapper对象

书接上文 MyBatis – 执行流程 我们通过SqlSession获取到了UserMapper对象&#xff0c;代码如下&#xff1a; // 获取SqlSession对象 SqlSession sqlSession sqlSessionFactory.openSession();// 执行查询操作 try {// 获取映射器接口UserMapper userMapper sqlSession.get…

C语言----字节对齐

一&#xff1a;字节对齐的概念 针对字节对齐&#xff0c;百度百科的解释如下&#xff1a; 字节对齐是字节按照一定规则在空间上排列&#xff0c;字节(Byte)是计算机信息技术用于计量存储容量和传输容量的一种计量单位&#xff0c;一个字节等于8位二进制数&#xff0c;在UTF-8编…

PS设计技巧01

大部分切图工作都是在PS中完成的 1、如何得知宽度和高度&#xff0c;先截个图&#xff1a; 2、找个文件夹&#xff0c;把截取的图片放进去&#xff0c;然后ctrl o 把图片文件放进去 3、存入图片&#xff0c;我们用的是网页图片&#xff0c;用的是ctrl r键&#xff0c;调出标尺…

记录电赛色块追踪部分

代码其实也很简单&#xff0c;我只不过加入了按键控制暂停、蜂鸣器、led和如何控制追踪的效果&#xff08;调PID&#xff09;。B站的那些大神早早地完成了要求&#xff0c;我犯了一个不好地错误&#xff0c;企图三连让他们分享思路&#xff0c;这是不对的&#xff0c;电赛本身的…

python之prettytable库的使用

文章目录 一 什么是prettytable二 prettytable的简单使用1. 添加表头2. 添加行3. 添加列4. 设置对齐方式4. 设置输出表格样式5. 自定义边框样式6. 其它功能 三 prettytable在实际中的使用 一 什么是prettytable prettytable是Python的一个第三方工具库&#xff0c;用于创建漂亮…

谷粒商城第九天-解决商品品牌问题以及前后端使用检验框架检验参数

目录 一、总述 二、商品分类问题 三、前端检验 四、后端检验 五、总结 一、总述 在完成完商品分类的时候&#xff0c;后来测试的时候还是发现了一些问题&#xff0c;现在将其进行解决&#xff0c;问题如下&#xff1a; 1. 取消显示的时候&#xff0c;如果取消了显示&…