要想了解ServletContextListener,先看看web.xml中的<listener>配置。

一)web.xml中的内容载入顺序:

首先能够肯定的是,载入顺序与它们在 web.xml 文件里的先后顺序无关。

即不会由于 filter 写在 listener 的前面而会先载入 filter。终于得出的结论是:listener -> filter -> servlet

        同一时候还存在着这样一种配置节:context-param,它用于向 ServletContext 提供键值对,即应用程序上下文信息。我们的 listener, filter 等在初始化时会用到这些上下文中的信息,那么 context-param 配置节是不是应该写在 listener 配置节前呢?实际上 context-param 配置节可写在任何位置,因此真正的载入顺序为:context-param -> listener -> filter -> servlet

        对于某类配置节而言,与它们出现的顺序是有关的。

以 filter 为例。web.xml 中当然能够定义多个 filter,与 filter 相关的一个配置节是 filter-mapping,这里一定要注意,对于拥有同样 filter-name 的 filter 和 filter-mapping 配置节而言。filter-mapping 必须出如今 filter 之后。否则当解析到 filter-mapping 时。它所相应的 filter-name 还没有定义。web 容器启动时初始化每一个 filter
时,是依照 filter 配置节出现的顺序来初始化的,当请求资源匹配多个 filter-mapping 时,filter 拦截资源是依照 filter-mapping 配置节出现的顺序来依次调用 doFilter() 方法的。

    servlet 同 filter 类似 ,此处不再赘述。

       由此,能够看出,web.xml 的载入顺序是:context-param -> listener -> filter -> servlet ,而同个类型之间的实际程序调用的时候的顺序是依据相应的 mapping 的顺序进行调用的。

二)ServletContextListener 是什么:从上面载入顺序分享一下,ServletContextListener 就是一个监听器。

        ServletContext 被 Servlet 程序用来与 Web 容器通信。

比如写日志,转发请求。每个 Web 应用程序含有一个Context,被Web应用内的各个程序共享。

由于Context能够用来保存资源而且共享,所以我所知道的 ServletContext 的最大应用是Web缓存----把不常常更改的内容读入内存。所以server响应请求的时候就不须要进行慢速的磁盘I/O了。

       ServletContextListener 是 ServletContext 的监听者,假设 ServletContext 发生变化,如server启动时 ServletContext 被创建,server关闭时 ServletContext 将要被销毁。

       在JSP文件里。application 是 ServletContext 的实例,由JSP容器默认创建。Servlet 中调用 getServletContext()方法得到 ServletContext 的实例。

三)ServletContextListener 可以做些什么:一切你想做的,就是一个监听器可以做的事。

1.设计缓存:

思路:

缓存的思路大概是:

    1)server启动时,ServletContextListener 的 contextInitialized()方法被调用,所以在里面创建好缓存。能够从文件里或者从数据库中读取取缓存内容生成类,用 ervletContext.setAttribute()方法将缓存类保存在 ServletContext 的实例中。

   2)程序使用 ServletContext.getAttribute()读取缓存。

假设是 JSP。使用a pplication.getAttribute()。假设是 Servlet。使用 getServletContext().getAttribute()。

假设缓存发生变化(如訪问计数),你能够同一时候更改缓存和文件/数据库。

或者你等 变化积累到一定程序再保存。也能够在下一步保存。

    3)server将要关闭时,ServletContextListener 的 contextDestroyed()方法被调用,所以在里面保存缓存的更改。将更改后的缓存保存回文件或者数据库,更新原来的内容。

import User; //my own class
import DatabaseManager; // my own class
import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener; public class MyContextListener implements ServletContextListener {
private ServletContext context = null; public void contextInitialized(ServletContextEvent event) {
context = event.getServletContext();
User user = DatabaseManager.getUserById(1);
context.setAttribute("user1", user);
} public void contextDestroyed(ServletContextEvent event) {
User user = (User)context.getAttribute("user1");
DatabaseManager.updateUserData(user);
this.context = null;
}
}

2)推断一个配置文件的编码格式:

public class InitProperties implements ServletContextListener {

	private static final Logger logger = Logger
.getLogger(InitProperties.class); @Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub }
/**
* 该监听器仅仅用于初始化时监听配置文件是否是utf-8编码 且仅仅在初始化时运行一次 对兴许的各种请求无影响
* **/
@Override
public void contextInitialized(ServletContextEvent arg0) { //载入文件的编码格式 查看是否是utf-8类型的
try {
String fileUrl = PropertiesHander.class.getResource("/evoucher.conf").toString();
fileUrl = fileUrl.replace("file:",""); File file = new File(fileUrl);
InputStream ios = new java.io.FileInputStream(file);
byte[] b = new byte[3]; try {
ios.read(b);
ios.close();
} catch (IOException e) { logger.error("检測编码载入时关闭流出现载入异常");
} //默认编码是 23 23 23 的 相同能够载入这样的默认的编码
if (b[0] == 35 && b[1] == 35 && b[2] == 35) {
logger.info(file.getName() + ":编码为默认编码");
}
//utf-8编码的首字母是 ef bb bf
else if (b[0] == -17 && b[1] == -69 && b[2] == -65) {
logger.info(file.getName() + ":编码为UTF-8");
} else
{
try{
// logger.error(file.getName() + "文件编码格式不是UTF-8编码。请又一次确定编码格式!");
throw new EVoucherException(file.getName() + "文件编码格式不是UTF-8编码,请又一次确定编码格式!");
}
catch(EVoucherException e){
// logger.error(e);
EVoucherException.getEVException(null, e, logger);
System.exit(0); } } } catch (FileNotFoundException e) { logger.error("检測编码时载入文件出现异常"); } } }

四)布署 ServletContextListener

<listener>
<listener-class>MyServletContextListener</listener-class>
</listener>
<!-- 自己主动监听配置文件是否是utf-8编码 -->
<listener>
<listener-class>assp.evoucher.common.util.InitProperties</listener-class>
</listener>

web.xml中的ServletContextListener的更多相关文章

  1. JavaEE web.xml 中ContextLoaderListener的解析

    ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息.因为它实现了ServletContextListener这个接口,在 ...

  2. web.xml中listener作用及使用

    一.WebContextLoaderListener 监听类 它能捕捉到server的启动和停止,在启动和停止触发里面的方法做对应的操作! 它必须在web.xml 中配置才干使用,是配置监听类的 二. ...

  3. web.xml中常用元素的解读

    前言 针对一个项目而言,通常会有几类XML文件需要书写. web.xml spring-context.xml spring-mvc.xml other.xml ... 不管有多少配置文件,可以肯定的 ...

  4. 【转】web.xml中的contextConfigLocation在spring中的作用

    一.spring中如何使用多个xml配置文件 1.在web.xml中定义contextConfigLocation参数,Spring会使用这个参数去加载所有逗号分隔的xml文件,如果没有这个参数,sp ...

  5. 如何把web.xml中的context-param、Servlet、Listener和Filter定义添加到SpringBoot中

    把传统的web项目迁移到SpringBoot中,少不了web.xml中的context-param.Servlet.Filter和Listener等定义的迁移. 对于Servlet.Filter和Li ...

  6. Spring中,applicationContext.xml 配置文件在web.xml中的配置详解

    一.首先写一下代码结构. 二.再看web.xml中的配置情况. <?xml version="1.0" encoding="UTF-8"?> < ...

  7. (转)web.xml中的contextConfigLocation在spring中的作用

    (转)web.xml中的contextConfigLocation在spring中的作用   一.Spring如何使用多个xml配置文件 1.在web.xml中定义contextConfigLocat ...

  8. 在web.xml中配置监听器来控制ioc容器生命周期

    5.整合关键-在web.xml中配置监听器来控制ioc容器生命周期 原因: 1.配置的组件太多,需保障单实例 2.项目停止后,ioc容器也需要关掉,降低对内存资源的占用. 项目启动创建容器,项目停止销 ...

  9. web.xml中Filter,Listener,Servlet的区别

    一.Servlet Servlet是基本的服务端程序,他来自接口Servlet,接口中有方法service.而Servlet的一个重要实现类,则是tomcat服务器的核心,那就是HttpServlet ...

随机推荐

  1. Global Round 2

    A - Ilya and a Colorful Walk CodeForces - 1119A Ilya lives in a beautiful city of Chordalsk. There a ...

  2. <a>标签的href 与 onclick 使用

    链接的onclick 事件被先执行,其次是href属性下的动作(页面跳转,或 javascript 伪链接): 假设链接中同时存在href 与onclick,如果想让href 属性下的动作不执行,on ...

  3. (16) Cloudflare pki公钥基础设施

    该工具组共有8个工具 1.cfssl 常用的可用指令: sign signs a certificate bundle build a certificate bundle genkey genera ...

  4. c++_方格填数(最新方法)

      方格填数 如下的10个格子 +--+--+--+ | | | |+--+--+--+--+| | | | |+--+--+--+--+| | | |+--+--+--+ (如果显示有问题,也可以参 ...

  5. 分分钟钟学会Python - 函数(function)

    函数(function) 1 基本结构 本质:将多行代码拿到别处并起个名字,以后通过名字就可以找到这行代码并执行 应用场景: 代码重复执行 代码量很多超过一屏,可以选择通过函数进行代码的分割 写代码方 ...

  6. 论MySQL中如何代替Oracle中select into new_table from old_table

    v_receipt         warehouse_receipt%ROWTYPE;-- 这里创建表类型,v_receipt复刻了warehouse_receipt的类型(相当于拥有了所有相同的字 ...

  7. 【数据传输 1】服务器—>客户端之间的数据类型转换

    导读:在做项目的时候,在controller中,将List数据类型转换为了JSON字符串,那么,为什么要将其数据转换为JOSN呢?这样的转换是否是必须的,在这个转换过程中,又经过了那些步骤?注:本篇博 ...

  8. codeforces 303 div2 E

    赤裸裸的最短路,需要注意下枚举过程就好了.直接贴上别人的代码,发现他的代码挺符合我的风格,以后就这样写了. #include <bits/stdc++.h> ]; ]; ]; ]; vec ...

  9. isNaN+parseFloat进行统计以及对NaN的处理【JS验证数字】

    今天遇到这么一个需求: 对数据进行统计,可是在统计的时候parseFloat的时候出来一个NaN.后来用isNaN判断,如果是NaN,就给其设置一个初值. 先看对两个方法的解释 parseFloat: ...

  10. AlertDialog自定义

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...