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.*" %>



     测试ServletContextListener 
    


下面是直接从application中取出数据库连接,
并执行查询后的结果
<% Connection conn = (Connection)application.getAttribute("conn"); // 创建Statement对象 Statement stmt = conn.createStatement(); // 执行查询 ResultSet rs = stmt.executeQuery("select * from news_inf"); %> <% // 遍历结果集 while(rs.next()) { %> <% } %>
<%=rs.getString(1)%> <%=rs.getString(2)%>

三 测试

ServletContextAttributeListener监听器实战_第1张图片

日志文件输出

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

 

你可能感兴趣的:(JSP,JSP)