要想了解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. poj3537 Crosses ans Crosses

    题目描述 题解: 一道非常简单的$SG$函数应用. 对于一个长度求它的$SG$函数,然后判断是否为$0$即可. 代码: #include<cstdio> #include<cstri ...

  2. set指令详解

    set指令详解 功能说明:设置shell 语 法:set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...] 说 明:设置或取消设置shell选项 ...

  3. iframe的操作switch_to_frame使用方法.

    一.frame和iframe区别 Frame与Iframe两者可以实现的功能基本相同,不过Iframe比Frame具有更多的灵活性. frame是整个页面的框架,iframe是内嵌的网页元素,也可以说 ...

  4. LeetCode(87) Gray Code

    题目 The gray code is a binary numeral system where two successive values differ in only one bit. Give ...

  5. 1. node.js环境搭建 第一行代码

    一.NodeJs简介 NodeJS官网上的介绍: Node.js is a platform built on  Chrome's JavaScript runtime  for easily bui ...

  6. 大数据学习——VMware安装

    ---恢复内容开始--- 一.下载VMware,安装 二.新建虚拟机 1.FIle-->new virtual machine 后面进入硬件资源分配,其中cpu给1个,内存至少给1G,网卡的选择 ...

  7. mq推送消息

    场景:BDM(实名制系统)同步数据到CRNS(实名制系统) 一,首先建个队列,队列名字为 bdm_empolyeeinfo_crns 二,applicationContext-rabbitmq.xml ...

  8. POJ1450:Gridland 【杂题】

    题目大意:先给出了TSP的背景,然后给出一个n*m的单位格点的图,图中除边缘上的点与八个方向的点有边连接,距离为欧拉距离,求从左上角出发的TSP 思路:从水题列表中看到的题,但看一开始给出的backg ...

  9. MySQL性能优化的21个最佳实践 和 mysql使用索引【转载】

    今天,数据库的操作越来越成为整个应用的性能瓶颈了,这点对于Web应用尤其明显.关于数据库的性能,这并不只是DBA才需要担心的事,而这更是我 们程序员需要去关注的事情.当我们去设计数据库表结构,对操作数 ...

  10. P1396 营救 洛谷

    https://www.luogu.org/problem/show?pid=1396 题目描述 “咚咚咚……”“查水表!”原来是查水表来了,现在哪里找这么热心上门的查表员啊!小明感动的热泪盈眶,开起 ...