Listener可以监听容器中某一执行动作,并根据其要求做出相应的响应。 常用的Web事件的监听接口如下:

ServletContextListener:用于监听Web的启动及关闭 ServletContextAttributeListener:

用于监听ServletContext范围内属性的改变 ServletRequestListener:

用于监听用户请求 ServletRequestAttributeListener:

用于监听ServletRequest范围属性的改变 HttpSessionListener:

用于监听用户session的开始及结束 HttpSessionAttributeListener:

用于监听HttpSession范围内的属性改变:

栗子:参考https://www.journaldev.com/1945/servletcontextlistener-servlet-listener-example#servlet-listener-example

import java.sql.Connection;

public class DBConnectionManager {

private String dbURL;
private String user;
private String password;
private Connection con;

public DBConnectionManager(String url, String u, String p){
this.dbURL=url;
this.user=u;
this.password=p;
//create db connection now

}

public Connection getConnection(){
return this.con;
}

public void closeConnection(){
//close DB connection here
}
}

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextAttributeListener implements ServletContextAttributeListener {

public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("ServletContext attribute added::{"+servletContextAttributeEvent.getName()+","+servletContextAttributeEvent.getValue()+"}");
}

public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("ServletContext attribute replaced::{"+servletContextAttributeEvent.getName()+","+servletContextAttributeEvent.getValue()+"}");
}

public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("ServletContext attribute removed::{"+servletContextAttributeEvent.getName()+","+servletContextAttributeEvent.getValue()+"}");
}

}

@WebListener
public class AppContextListener implements ServletContextListener {

public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext ctx = servletContextEvent.getServletContext();

String url = ctx.getInitParameter("DBURL");
String u = ctx.getInitParameter("DBUSER");
String p = ctx.getInitParameter("DBPWD");

//create database connection from init parameters and set it to context
DBConnectionManager dbManager = new DBConnectionManager(url, u, p);
ctx.setAttribute("DBManager", dbManager);
System.out.println("Database connection initialized for Application.");
}

public void contextDestroyed(ServletContextEvent servletContextEvent) {
ServletContext ctx = servletContextEvent.getServletContext();
DBConnectionManager dbManager = (DBConnectionManager) ctx.getAttribute("DBManager");
dbManager.closeConnection();
System.out.println("Database connection closed for Application.");

}

}

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

@WebListener
public class MyServletRequestListener implements ServletRequestListener {

public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
ServletRequest servletRequest = servletRequestEvent.getServletRequest();
System.out.println("ServletRequest destroyed. Remote IP="+servletRequest.getRemoteAddr());
}

public void requestInitialized(ServletRequestEvent servletRequestEvent) {
ServletRequest servletRequest = servletRequestEvent.getServletRequest();
System.out.println("ServletRequest initialized. Remote IP="+servletRequest.getRemoteAddr());
}

}

@WebListener
public class MySessionListener implements HttpSessionListener {

public void sessionCreated(HttpSessionEvent sessionEvent) {
System.out.println("Session Created:: ID="+sessionEvent.getSession().getId());
}

public void sessionDestroyed(HttpSessionEvent sessionEvent) {
System.out.println("Session Destroyed:: ID="+sessionEvent.getSession().getId());
}

}

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("begin to handle request....");
ServletContext ctx = request.getServletContext();
ctx.setAttribute("User", "Pankaj");
String user = (String) ctx.getAttribute("User");
ctx.removeAttribute("User");

HttpSession session = request.getSession();
session.invalidate();

PrintWriter out = response.getWriter();
out.write("Hi "+user);
}

}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletListenerExample</display-name>

<context-param>
<param-name>DBUSER</param-name>
<param-value>pankaj</param-value>
</context-param>
<context-param>
<param-name>DBPWD</param-name>
<param-value>password</param-value>
</context-param>
<context-param>
<param-name>DBURL</param-name>
<param-value>jdbc:mysql://localhost/mysql_db</param-value>
</context-param>

<listener>
<listener-class>com.journaldev.listener.AppContextListener</listener-class>
</listener>
<listener>
<listener-class>com.journaldev.listener.AppContextAttributeListener</listener-class>
</listener>
<listener>
<listener-class>com.journaldev.listener.MySessionListener</listener-class>
</listener>
<listener>
<listener-class>com.journaldev.listener.MyServletRequestListener</listener-class>
</listener>
</web-app>

启动时:

ServletContext attribute added::{DBManager,com.journaldev.db.DBConnectionManager@18140878}
Database connection initialized for Application.
ServletContext attribute added::{org.apache.jasper.compiler.TldLocationsCache,org.apache.jasper.compiler.TldLocationsCache@45cc5809}

浏览器输入:http://localhost:8084/ServletListenerExample/MyServlet

输出:

ServletRequest initialized. Remote IP=127.0.0.1
begin to handle request....
ServletContext attribute added::{User,Pankaj}
ServletContext attribute removed::{User,Pankaj}
Session Created:: ID=349003AB937F7C54BCCB4DE4506F5958
Session Destroyed:: ID=349003AB937F7C54BCCB4DE4506F5958
ServletRequest destroyed. Remote IP=127.0.0.1

关闭时:Database connection closed for Application.

web.xml中自定义Listener的更多相关文章

  1. web.xml 中的listener、 filter、servlet 加载顺序及其详解

    在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是 ...

  2. web.xml 中的listener、 filter、servlet 加载顺序

    在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是 ...

  3. web.xml 中的listener、filter、servlet 加载顺序及其【配置详解】

    在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是 ...

  4. 转:web.xml 中的listener、 filter、servlet 加载顺序及其详解

    在项目中总会遇到一些关于加载的优先级问题,刚刚就遇到了一个问题,由于项目中使用了quartz任务调度,quartz在web.xml中是使用listener进行监听的,使得在tomcat启动的时候能马上 ...

  5. web.xml 中的listener、 filter、servlet 加载顺序及其详解(转)

    在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是 ...

  6. lisener在web.xml中设置

    /* * servlet监听器开发步骤: * 1.写一个类实现XXXListener接口(6个=3个容器+3个对容器中属性进行操作) * 2.在web.xml中配置<listener> - ...

  7. 160715、在web.xml中注册IntrospectorCleanupListener解决Quartz等框架可能产生的内存泄露问题

    增加方式如下:web.xml中加入  <listener>    <listener-class>org.springframework.web.util.Introspect ...

  8. web.xml中的ServletContextListener

    要想了解ServletContextListener,先看看web.xml中的<listener>配置. 一)web.xml中的内容载入顺序: 首先能够肯定的是,载入顺序与它们在 web. ...

  9. web.xml中的主要元素说明(listener, filter, servlet)

    web.xml中加载的顺序为:context-param ---> listener ---> filter ---> servlet. listener:主要针对的是对象的操作,如 ...

随机推荐

  1. React 之 组件生命周期

    React 之 组件生命周期 理解1) 组件对象从创建到死亡它会经历特定的生命周期阶段2) React组件对象包含一系列的勾子函数(生命周期回调函数), 在生命周期特定时刻回调3) 我们在定义组件时, ...

  2. nmcli命令行修改网络连接名称

    目前在网上能找到的文章中,使用nmcli命令修改Linux系统中网卡连接的名称都是先创建新的连接,然后删除旧的连接的方式 此种方式其实完全不恰当,简直就是在浪费时间,nmcli命令本身就提供了直接修改 ...

  3. [考试总结]noip模拟17

    爆零了! 菜爆了 弱展了 垃爆了 没有什么可以掩饰你的菜了 这次考试为我带来了第一个 \(\color{red}{ \huge{0}}\) 分,十分欣慰.... 最近的暴力都打不对,你还想什么正解?? ...

  4. 2021零售商业智能(BI)的 8大好处

    零售业的商业智能现在比以往任何时候都更加重要.客户数据不仅可以用来击败竞争对手,还可以用来识别模式和行为,确定哪些产品和服务适合当下销售,以及如何瞄准新市场. 什么是零售业的商业智能? 商业智能是使用 ...

  5. HashSet 的实现原理

    HashSet 概述 对于 HashSet 而言,它是基于 HashMap 实现的,底层采用 HashMap 来保存元素,所以如果对 HashMap 比较熟悉了,那么学习 HashSet 也是很轻松的 ...

  6. 除了Swagger UI,你还能选择 IGeekFan.AspNetCore.RapiDoc

    IGeekFan.AspNetCore.RapiDoc 看到博客园上的这个文章,说了下Knife4J,评论里有人推荐RapiDoc,放了几个图,看了下,还不错. 心里 便有个想法,借着上次研究 Kni ...

  7. Go测试技术分享(一):场景化接口Case编写

    一.前言 本人负责的支付清结算方向的测试工作,在测试项目中,会出现流程化的接口调用,请求完一个接口后,继续请求另一个接口(这里的接口可以指Http,也指rpc接口),这里以一个真实场景为例:用户在平台 ...

  8. JAVA集合类概览

    带着问题来阅读 1.Java有哪些集合 2.不同集合的应用场景分别是哪些 3.哪些实现类是线程安全的 4.为什么Java集合不能存放基本类型 5.集合的fail-fast和fail-safe是什么 J ...

  9. ERROR: database "db" is being accessed by other users

    执行DROP DATABASE testdb;的时候提示: ERROR: database "testdb" is being accessed by other users DE ...

  10. WPF Combox实现下拉多选,可选中多个值

    自定义多选MultiCombox,可以实现下拉列表多选 using System; using System.Collections.Generic; using System.Collections ...