ServletContextAttributeListener监听器实战

一 代码

package lee;

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

@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 + "的属性被替换了!");
    }
}

二 测试JSP

<%@ 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>

三 测试

日志文件输出

org.apache.catalina.connector.RequestFacade@2b5e78d5范围内名为org.apache.catalina.ASYNC_SUPPORTED,值为true的属性被替换了!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值