吴裕雄--天生自然轻量级JAVA EE企业应用开发Struts2Sping4Hibernate整合开发学习笔记:Listener介绍

<%--
网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
author  yeeku.H.lee kongyeeku@163.com
version  1.0
Copyright (C), 2001-2016, yeeku.H.Lee
This program is protected by copyright laws.
Program Name:
Date: 
--%>

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> 测试ServletContextListener </title>
    <meta name="website" content="http://www.crazyit.org" />
</head>
<body>
下面是直接从application中取出数据库连接,<br/>
并执行查询后的结果<br/>
<%
Connection conn = (Connection)application.getAttribute("conn");
// 创建Statement对象
Statement stmt = conn.createStatement();
// 执行查询
ResultSet rs = stmt.executeQuery("select * from news_inf");
%>
<table bgcolor="#9999dd" border="1" width="300">
<%
// 遍历结果集
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
</tr>
<%
}
%>
<table>
</body>
</html>
<%--
网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
author  yeeku.H.lee kongyeeku@163.com
version  1.0
Copyright (C), 2001-2016, yeeku.H.Lee
This program is protected by copyright laws.
Program Name:
Date: 
--%>

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> 用户在线信息 </title>
    <meta name="website" content="http://www.crazyit.org" />
</head>
<body>
在线用户:
<table width="400" border="1">
<%
Map<String , String> online = (Map<String , String>)application
    .getAttribute("online");
for (String sessionId : online.keySet())
{%>
<tr>
    <td><%=sessionId%>
    <td><%=online.get(sessionId)%>
</tr>
<%}%>
</body>
</html>
<?xml version="1.0" encoding="GBK"?>
<!-- 定义生成文件的project根元素,默认的target为空 -->
<project name="web" basedir="." default="">
    <!-- 定义三个简单属性 -->
    <property name="src" value="src"/>
    <property name="classes" value="classes"/>
    <!-- 定义一组文件和目录集 -->
    <path id="classpath">
        <fileset dir="lib">
            <include name="**/*.jar"/>
        </fileset>
        <pathelement path="${classes}"/>
    </path>
    <!-- 定义compile target,用于编译Java源文件 -->
    <target name="compile" description="编译Java源文件">
        <!-- 先删除classes属性所代表的文件夹 -->
        <delete dir="${classes}"/>
        <!-- 创建classes属性所代表的文件夹 -->
        <mkdir dir="${classes}"/>
        <copy todir="${classes}">
            <fileset dir="${src}">
                <exclude name="**/*.java"/>
            </fileset>
        </copy>
        <!-- 编译Java文件,编译后的class文件放到classes属性所代表的文件夹内 -->
        <javac destdir="${classes}" debug="true" includeantruntime="yes"
            deprecation="false" optimize="false" failonerror="true">
            <!-- 指定需要编译的Java文件所在的位置 -->
            <src path="${src}"/>
            <!-- 指定编译Java文件所需要第三方类库所在的位置 -->
            <classpath refid="classpath"/>
        </javac>
    </target>
</project>
<?xml version="1.0" encoding="GBK"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
    <!-- 配置第一个参数:driver -->
    <context-param>
        <param-name>driver</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </context-param>
    <!-- 配置第二个参数:url -->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/javaee</param-value>
    </context-param>
    <!-- 配置第三个参数:user -->
    <context-param>
        <param-name>user</param-name>
        <param-value>root</param-value>
    </context-param>
    <!-- 配置第四个参数:pass -->
    <context-param>
        <param-name>pass</param-name>
        <param-value>32147</param-value>
    </context-param>

    <listener>
        <!-- 指定Listener的实现类 -->
        <listener-class>lee.GetConnListener</listener-class>
    </listener>

</web-app>
package lee;

import javax.servlet.*;
import javax.servlet.annotation.*;/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
@WebListener
public class MyServletContextAttributeListener
    implements ServletContextAttributeListener
{
    // 当程序向application范围添加属性时触发该方法
    public void attributeAdded(ServletContextAttributeEvent event)
    {
        ServletContext application = event.getServletContext();
        // 获取添加的属性名和属性值
        String name = event.getName();
        Object value = event.getValue();
        System.out.println(application + "范围内添加了名为"
            + name + ",值为" + value + "的属性!");
    }
    // 当程序从application范围删除属性时触发该方法
    public void attributeRemoved(ServletContextAttributeEvent event)
    {
        ServletContext application = event.getServletContext();
        // 获取被删除的属性名和属性值
        String name = event.getName();
        Object value = event.getValue();
        System.out.println(application + "范围内名为"
            + name + ",值为" + value + "的属性被删除了!");
    }
    // 当application范围的属性被替换时触发该方法
    public void attributeReplaced(ServletContextAttributeEvent event)
    {
        ServletContext application = event.getServletContext();
        // 获取被替换的属性名和属性值
        String name = event.getName();
        Object value = event.getValue();
        System.out.println(application + "范围内名为"
            + name + ",值为" + value + "的属性被替换了!");
    }
}
package lee;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;import java.util.*;/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
@WebListener
public class OnlineListener
    implements HttpSessionListener
{
    // 当用户与服务器之间开始session时触发该方法
    public void sessionCreated(HttpSessionEvent se)
    {
        HttpSession session = se.getSession();
        ServletContext application = session.getServletContext();
        // 获取session ID
        String sessionId = session.getId();
        // 如果是一次新的会话
        if (session.isNew())
        {
            String user = (String)session.getAttribute("user");
            // 未登录用户当游客处理
            user = (user == null) ? "游客" : user;
            Map<String , String> online = (Map<String , String>)
                application.getAttribute("online");
            if (online == null)
            {
                online = new Hashtable<String , String>();
            }
            // 将用户在线信息放入Map中
            online.put(sessionId , user);
            application.setAttribute("online" , online);
        }
    }
    // 当用户与服务器之间session断开时触发该方法
    public void sessionDestroyed(HttpSessionEvent se)
    {
        HttpSession session = se.getSession();
        ServletContext application = session.getServletContext();
        String sessionId = session.getId();
        Map<String , String> online = (Map<String , String>)
            application.getAttribute("online");
        if (online != null)
        {
            // 删除该用户的在线信息
            online.remove(sessionId);
        }
        application.setAttribute("online" , online);
    }
}
package lee;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */

@WebListener
public class RequestListener
    implements ServletRequestListener , ServletRequestAttributeListener
{
    // 当用户请求到达、被初始化时触发该方法
    public void requestInitialized(ServletRequestEvent sre)
    {
        HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
        System.out.println("----发向" + request.getRequestURI()
            + "请求被初始化----");    }
    // 当用户请求结束、被销毁时触发该方法
    public void requestDestroyed(ServletRequestEvent sre)
    {
        HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
        System.out.println("----发向" + request.getRequestURI()
            + "请求被销毁----");
    }
    // 当程序向request范围添加属性时触发该方法
    public void attributeAdded(ServletRequestAttributeEvent event)
    {
        ServletRequest request = event.getServletRequest();
        // 获取添加的属性名和属性值
        String name = event.getName();
        Object value = event.getValue();
        System.out.println(request + "范围内添加了名为"
            + name + ",值为" + value + "的属性!");
    }
    // 当程序从request范围删除属性时触发该方法
    public void attributeRemoved(ServletRequestAttributeEvent event)
    {
        ServletRequest request = event.getServletRequest();
        // 获取被删除的属性名和属性值
        String name = event.getName();
        Object value = event.getValue();
        System.out.println(request + "范围内名为"
            + name + ",值为" + value + "的属性被删除了!");
    }
    // 当request范围的属性被替换时触发该方法
    public void attributeReplaced(ServletRequestAttributeEvent event)
    {
        ServletRequest request = event.getServletRequest();
        // 获取被替换的属性名和属性值
        String name = event.getName();
        Object value = event.getValue();
        System.out.println(request + "范围内名为"
            + name + ",值为" + value + "的属性被替换了!");
    }
}
package lee;

import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
@WebListener
public class GetConnListener implements ServletContextListener
{
    // 应该启动时,该方法被调用。
    public void contextInitialized(ServletContextEvent sce)
    {
        try
        {
            // 取得该应用的ServletContext实例
            ServletContext application = sce.getServletContext();
            // 从配置参数中获取驱动
            String driver = application.getInitParameter("driver");
            // 从配置参数中获取数据库url
            String url = application.getInitParameter("url");
            // 从配置参数中获取用户名
            String user = application.getInitParameter("user");
            // 从配置参数中获取密码
            String pass = application.getInitParameter("pass");
            // 注册驱动
            Class.forName(driver);
            // 获取数据库连接
            Connection conn = DriverManager.getConnection(url
                , user , pass);
            // 将数据库连接设置成application范围内的属性
            application.setAttribute("conn" , conn);
        }
        catch (Exception ex)
        {
            System.out.println("Listener中获取数据库连接出现异常"
                + ex.getMessage());
        }
    }
    // 应该关闭时,该方法被调用。
    public void contextDestroyed(ServletContextEvent sce)
    {
        // 取得该应用的ServletContext实例
        ServletContext application = sce.getServletContext();
        Connection conn = (Connection)application.getAttribute("conn");
        // 关闭数据库连接
        if (conn != null)
        {
            try
            {
                conn.close();
            }
            catch (SQLException ex)
            {
                ex.printStackTrace();
            }
        }
    }
}
原文地址:https://www.cnblogs.com/tszr/p/12364019.html