监听器

public class UserListener implements HttpSessionBindingListener { // 不需要在web.xml文件中配置监听器
    // 默认的在线人数
    public static int ONLINE_NUM = 0;
    private String name;

    // 在往session中添加数据的时候 会触发的事件
    public void valueBound(HttpSessionBindingEvent event) {
        System.out.println("进入了 人数+++++++++++++++1");
        ONLINE_NUM++;
    }

    /**
     * 01.session失效   session.invalidate()
     * 02.session超时
     * 03.session清除指定属性得到时候,改变属性的时候
     */
    public void valueUnbound(HttpSessionBindingEvent event) {
        System.out.println("进入了 人数-----------------1");
        ONLINE_NUM--;
    }

    // 对应的带参构造方法
    public UserListener(String name) {
        super();
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
创建一个class实现HttpSessionBindingListener接口

实现了HttpSessionBindingListener接口的类 才能被监听,没有实现这个接口的类是无法被监听器监听的!不需要在web.xml文件中配置监听器类!

需要的界面

<body>
    <form action="doMain.jsp" method="post">
       <input  type="text"  name="userName"> 
       <button  type="submit">提交</button>
    </form>
  </body>
登录界面login.jsp
 <body>
  
  <%
   String  userName=request.getParameter("userName");
    if(userName==null||userName==""){  //判断用户是否输出数据
        response.sendRedirect("login.jsp");
    }else{   //有值
        UserListener user=new UserListener(userName);
         System.out.println("应该在触发器之前执行的代码..............");
         //触发器开始执行
         session.setAttribute("user", user);
         response.sendRedirect("onLine.jsp");
    }
  %>
  
  </body>
处理请求的界面doMain.jsp
<body>
    <h1>当前在线人数:<%=UserListener.ONLINE_NUM%></h1>
    
    <a href="out.jsp">退出登录</a>
    
  </body>
onLine.jsp页面
<body>
   <%
   session.invalidate();
   response.sendRedirect("onLine.jsp");
   %>
  </body>
退出登录out.jsp

实现了HttpSessionListener接口的类 能监听程序中所有的session! 需要在web.xml文件中配置监听器类!

public class UserSession implements HttpSessionListener {
    static { // 验证我们这个 UserSession 监听器的 启动时间 是服务器启动的时候 开启的
        System.out
                .println("UserSession静态代码块----------------------------------");
    }

    {
        System.out
                .println("UserSession普通代码块----------------------------------");
    }

    // 实例化
    public UserSession() {
        System.out.println("构造.....................");
    }

    // 获取ServletContext对象
    public void sessionCreated(HttpSessionEvent event) {
        ServletContext context = event.getSession().getServletContext();
        // 获取共享的数据
        Integer userCount = (Integer) context.getAttribute("userCount");
        // 因为第一次肯定为空 需要做非空验证
        if (userCount == null) {
            userCount = new Integer(1);
        } else {
            userCount = userCount + 1;
        }
        // 存入共享的数据
        context.setAttribute("userCount", userCount);
        System.out.println("进了+++++++++++++++++++++++1");
    }

    /**                                         
     * 01.session失效   session.invalidate()      
     * 02.session超时                             
     */
    public void sessionDestroyed(HttpSessionEvent event) {
        ServletContext context = event.getSession().getServletContext();
        // 获取共享的数据
        Integer userCount = (Integer) context.getAttribute("userCount");
        // 因为第一次肯定为空 需要做非空验证
        if (userCount == null) {
            userCount = new Integer(0);
        } else {
            userCount = userCount - 1;
        }
        System.out.println("进了--------------------1");
        // 存入共享的数据
        context.setAttribute("userCount", userCount);
    }

}
创建一个监听器类实现了HttpSessionListener

在上面的实例代码中直接修改onLine.jsp的页面

<body>

    <h1>
        当前在线人数:
        <%=session.getServletContext().getAttribute("userCount")%>
    </h1>
    <a href="out.jsp">退出登录</a>

</body>
修改后的onLine.jsp

实现了ServletContextListener接口的类 能监听整个程序  需要在web.xml文件中配置监听器类!

public class DataListener implements ServletContextListener {// 全局的监听服务

    public void contextInitialized(ServletContextEvent event) {
        System.out.println("在服务器启动的时候进行初始化**************");
        try {
            // 初始化上下文信息
            Context context = new InitialContext();
            // 获取数据源的相关信息
            DataSource source = (DataSource) context
                    .lookup("java:comp/env/jdbc/news");
            event.getServletContext().setAttribute("DS", source);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("在服务器关闭的的时候销毁**************");
    }

}
创建一个监听类实现ServletContextListener

在tomcat中找到config文件夹下面的context.xml文件

<?xml version='1.0' encoding='utf-8'?>
<Context>

    <WatchedResource>WEB-INF/web.xml</WatchedResource>
<!--
name:数据源的名称
auth:容器类型
type:指定数据源的类型
username:用户名
password:密码
driverClassName:数据库驱动包
url:连接的地址
maxWait:最大的等待时间
maxIdle:设置最大的连接数
maxActive:重新连接
-->
    <Resource  name="jdbc/news" auth="Container"
       type="javax.sql.DataSource"
       username="wym"
       password="wym"
       driverClassName="com.mysql.jdbc.Driver"
       url="jdbc:mysql://127.0.0.1:3306/news"
       maxIdle="30"
       maxWait="10000"
       maxActive="1000"
    />    
</Context>
context.xml文件

之后创建一个页面,看能否拿到DataSource的值

<body>
  <%
  out.print(session.getServletContext().getAttribute("DS"));
  %>
  </body>
常见一个jsp界面

如果想更改新闻管理系统为数据源的方式  只需要更改BaseDao中的获取连接的方法即可

 public boolean getConnection() {
        try {
            // 初始化上下文信息
            Context context = new InitialContext();
            // 获取数据源的相关信息
            DataSource source = (DataSource) context
                    .lookup("java:comp/env/jdbc/news");

            con = source.getConnection();
        } catch (NamingException e) {
            e.printStackTrace();
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
BaseDao
原文地址:https://www.cnblogs.com/xtdxs/p/7094874.html