要想了解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. 读书笔记之《编程小白的第1本Python入门书》

    本书电子版下载地址:百度网盘 写在前面:你需要这本书的原因 有没有那一个瞬间,让你想要放弃学习编程? 在我决心开始学编程的时候,我为自己制定了一个每天编程1小时的计划,那时候工作很忙,我只能等到晚上9 ...

  2. 第九节:pandas打印设置

    get_option() :获取系统默认设置选项: set_option() :设置系统设置选项.

  3. tiles框架的definition讲解

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE tiles-definitions PUBL ...

  4. c#导出word文档

    为方便下次遇到不知道去哪找先把它存放在这里,以下是保存导出word主要类方法 public class BiultReportForm { /// <summary>word 应用对象 & ...

  5. SpringCloud源码地址

    SpringCloud实战源代码 https://github.com/springcloud/spring-cloud-code.git

  6. 【01】魔芋使用MDN的一点点经验

    [01]魔芋使用MDN的一点点经验     1,MDN地址: https://developer.mozilla.org/en-US/(下图)   2,建议看英文原文.因为中文翻译落后,并且有些翻译并 ...

  7. 在JavaScript中获取Map集合中的key和value值(前提是:既不知道key为什么值,也不知道value有哪些值)

  8. Food Delivery (区间DP)

    When we are focusing on solving problems, we usually prefer to stay in front of computers rather tha ...

  9. POJ1061青蛙的约会

    Description 两只青蛙在网上相识了,它们聊得很开心,于是觉得很有必要见一面.它们很高兴地发现它们住在同一条纬度线上,于是它们约定各自朝西跳,直到碰面为止.可是它们出发之前忘记了一件很重要的事 ...

  10. [luoguP1027] Car的旅行路线(Floyd)

    传送门 建图麻烦,建完图搞一遍Floyd就好了. ——代码 #include <iostream> #include <cstdio> #include <cmath&g ...