ServletContextAttributeListener的用法和实例

2)ServletContextAttributeListener:
ServletContextAttributeListener能监测到有人正在往ServletContext里添加属性。你可以采取相应的措施。
例 2.2.2.1
web.xml当中再加入一段话:
  <listener>
    <listener-class>com.MyServletContextAttributeListener</listener-class>
  </listener>
package com;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
public class MyServletContextAttributeListener implements ServletContextAttributeListener  {
    public void attributeAdded(ServletContextAttributeEvent arg0) {
        System.out.println("增加了" + arg0.getName() + " " +
                arg0.getValue() );
    }
    public void attributeRemoved(ServletContextAttributeEvent arg0) {
        System.out.println("去除了" + arg0.getName() + " " +
                arg0.getValue() );
    }
    public void attributeReplaced(ServletContextAttributeEvent arg0) {
        System.out.println("取代了" + arg0.getName() + " " +
                arg0.getValue()+"现在的新值是"+arg0.getServletContext().getAttribute(arg0.getName()) );
    }
}
随便做一个Servlet测试一下:
package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("add attribute");
        getServletContext().setAttribute("name", "马克-to-win");
        System.out.println("replace attribute");
        getServletContext().setAttribute("name", "mark-to-win");
        System.out.println("remove attribute");
        getServletContext().removeAttribute("name");
    }
}

更多请见:http://www.mark-to-win.com/index.html?content=Jsp/jspUrl.html&chapter=Jsp/jsp6_web.html#ServletContextAttributeListener

ServletContextAttributeListener的用法和实例ServletContextAttributeListener的用法和实例 qq_44638460 发布了0 篇原创文章 · 获赞 0 · 访问量 367 私信 关注
上一篇:Linux shell判断文件和文件夹是否存在


下一篇:ServletRequestAttributeListener的用法和实例