(1)域对象的通用的方法:
setAttribute(name,value)
--- 触发添加属性的监听器的方法
--- 触发修改属性的监听器的方法
getAttribute(name)
removeAttribute(name)
--- 触发删除属性的监听器的方法
(2)ServletContextAttibuteListener监听器
package com.itcast.attribute;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
public class MyServletContextAttributeListener implements ServletContextAttributeListener{
@Override
public void attributeAdded(ServletContextAttributeEvent arg0) {
System.out.println(arg0.getName());//添加域中的name
System.out.println(arg0.getValue());//添加域中的value
}
@Override
public void attributeRemoved(ServletContextAttributeEvent arg0) {
// TODO Auto-generated method stub
System.out.println(arg0.getName());//删除域中的name
System.out.println(arg0.getValue());//删除域中的value
}
@Override
public void attributeReplaced(ServletContextAttributeEvent arg0) {
System.out.println(arg0.getName());//获得修改前的name
System.out.println(arg0.getValue());//获得修改前的value
}
}
package com.itcast.attribute;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServletContextAttributeListener extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
//添加
servletContext.setAttribute("name", "tom");
//修改
servletContext.setAttribute("name", "lucy");
//删除
servletContext.removeAttribute("name");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}