ServletContextAttributeListener的用法和实例
ServletContextAttributeListener:
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
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");
}
}
运行这个servlet以后,console里的输出结果是:
add attribute
增加了name 马克-to-win
replace attribute
取代了name 马克-to-win现在的新值是mark-to-win
remove attribute
去除了name mark-to-win