ServletRequestAttributeListener的用法和实例
ServletRequestAttributeListener:
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
ServletRequestAttributeListener能监测到有人正在往ServletRequest里添加属性。你可以采取相应的措施。
例 2.2.6.1
package com;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
public class MyServletRequestAttributeListener implements ServletRequestAttributeListener {
public void attributeAdded(ServletRequestAttributeEvent arg0) {
System.out.println("增加了" + arg0.getName() + " " +
arg0.getValue() );
}
public void attributeRemoved(ServletRequestAttributeEvent arg0) {
System.out.println("去除了" + arg0.getName() + " " +
arg0.getValue() );
}
public void attributeReplaced(ServletRequestAttributeEvent arg0) {
System.out.println("取代了" + arg0.getName() + " " +
arg0.getValue()+"现在的新值是"+arg0.getServletRequest().getAttribute(arg0.getName()) );
}
}
web.xml加入下面这段话:
<listener>
<listener-class>com.MyServletRequestAttributeListener</listener-class>
</listener>
用下面这个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");
request.setAttribute("name", "马克-to-win");
System.out.println("replace attribute");
request.setAttribute("name", "mark-to-win");
System.out.println("remove attribute");
request.removeAttribute("name");
}
}
运行这个Servlet以后,console里的输出结果是:
add attribute
增加了name 马克-to-win
replace attribute
取代了name 马克-to-win现在的新值是mark-to-win
remove attribute
去除了name mark-to-win