zoukankan      html  css  js  c++  java
  • ServletContextListener作用 转

    ServletContext 被 Servlet 程序用来与 Web 容器通信。例如写日志,转发请求。每一个 Web 应用程序含有一个Context,被Web应用内的各个程序共享。因为Context可以用来保存资源并且共享,所以我所知道的 ServletContext 的最大应用是Web缓存----把不经常更改的内容读入内存,所以服务器响应请求的时候就不需要进行慢速的磁盘I/O了。

    ServletContextListener 是 ServletContext 的监听者,如果 ServletContext 发生变化,如服务器启动时 ServletContext 被创建,服务器关闭时 ServletContext 将要被销毁。

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

    我们使用缓存的思路大概是:

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

    程序使用 ServletContext.getAttribute()读取缓存。如果是 JSP,使用a pplication.getAttribute()。如果是 Servlet,使用 getServletContext().getAttribute()。如果缓存发生变化(如访问计数),你可以同时更改缓存和文件/数据库。或者你等 变化积累到一定程序再保存,也可以在下一步保存。

    服务器将要关闭时,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;
    }
    }
    布署 ServletContextListener
    你实现(implements)了 ServletContextListener 编译后,把它放在正确的WEB-INF/classes目录下,更改WEB-INF目录下的 web.xml文件,在web-app节点里添加

    ≤listener≥
    ≤listener-class≥MyServletContextListener≤/listener-class≥
    ≤/listener≥
  • 相关阅读:
    MyImages
    【优惠&正版】超级硬盘数据恢复软件(SuperRecovery)7.1正版注册码(39元一机终身授权,支持最新版)
    【2020年4月24日】TTradmin v2.3.2 简单好用的临时远程协助软件
    Radmin Center 1.54 测试版
    VS2015 编译原版 tightvnc 2.8.27 源码
    Centos 安装 Go 编译环境
    GHO文件安装到Vmware的两种姿势
    Radmin Server v3.5.2.1 汉化破解绿色版,完整版+精简版【20190505更新】
    系统服务监视、系统服务守护 ServiceMonitor
    API Monitor v2.0 Alpha-r13 (32+64) 汉化版
  • 原文地址:https://www.cnblogs.com/luckForever/p/7254265.html
Copyright © 2011-2022 走看看