对Request的监听分生命周期的监听,和Request上Attribute变化的监听两部分。
步骤1:编写 RequestListener
步骤2:配置web.xml
步骤3:testRequest.jsp
步骤4:测试
步骤 1 : 编写 RequestListener
RequestListener 实现接口 ServletRequestListener和ServletRequestAttributeListener
当新创建了一个Request的时候触发,只要访问了服务端的资源,就会创建一个Request,无论是jsp,servlet还是html
当本次请求结束的时候触发
当有新增属性时触发
当有替换属性时触发
当有移除属性时触发
package listener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class RequestListener implements ServletRequestListener, ServletRequestAttributeListener {
@Override
public void requestDestroyed(ServletRequestEvent arg0) {
System.out.println( "销毁了一个Request " );
}
@Override
public void requestInitialized(ServletRequestEvent arg0) {
System.out.println( "创建了一个Request " );
}
@Override
public void attributeAdded(ServletRequestAttributeEvent e) {
System.out.println( "request 增加属性 " );
System.out.println( "属性是" + e.getName());
System.out.println( "值是" + e.getValue());
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent arg0) {
System.out.println( "request 移除属性 " );
}
@Override
public void attributeReplaced(ServletRequestAttributeEvent arg0) {
System.out.println( "request 替换属性 " );
}
}
|
步骤 2 : 配置web.xml
< listener >
< listener-class >listener.RequestListener</ listener-class >
</ listener >
|
步骤 3 : testRequest.jsp
测试页面,先在request中设置test,然后替换,最后移出掉test
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setAttribute("test", 1);
request.setAttribute("test", 2);
request.removeAttribute("test");
%>
|
步骤 4 : 测试
访问页面
http: //127.0.0.1/testRequest.jsp
|
观察测试结果
更多内容,点击了解: https://how2j.cn/k/listener/listener-request/607.html