在web开发中,监听器不仅可以对Application监听,同时还可以对seesion和request对象进行监听;
该文章主要演示的是对request对象的创建和request属性的监听。
项目结构(红叉不需要关注,是maven环境的问题,不影响我们的主线)
web.xml
"1.0" encoding="UTF-8"?>
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
pom.xml
RequestAttrListener
public class RequestAttrListener implements ServletRequestAttributeListener{
public void attributeAdded(ServletRequestAttributeEvent event) {
System.out.println("request域添加了属性:" + event.getName() + "=" + event.getValue());
}
public void attributeRemoved(ServletRequestAttributeEvent event) {
System.out.println("request域删除了属性:" + event.getName() + "=" + event.getValue());
}
public void attributeReplaced(ServletRequestAttributeEvent event) {
System.out.println("request域修改了属性(这里展示的是被替换的):" + event.getName() + "=" + event.getValue());
}
}
RequestListener
public class RequestListener implements ServletRequestListener{
public void requestDestroyed(ServletRequestEvent even) {
System.out.println("request对象销毁了 ......");
}
public void requestInitialized(ServletRequestEvent even) {
System.out.println("request对象创建了 ......");
}
}
TestServlet
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("a", "aaaa");
request.setAttribute("a", "bbbb");
request.removeAttribute("a");
response.getOutputStream().print("over");
}
}
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<base href="<%=basePath%>">
"pragma" cOntent="no-cache">
"cache-control" cOntent="no-cache">
"servlet/test">点点
访问测试:
http://localhost:8080/listener/
结果解析:
这三行是http://localhost:8080/listener/生成的
request对象创建了 ......
request域修改了属性(这里展示的是被替换的):org.apache.catalina.ASYNC_SUPPORTED=true
request对象销毁了 ......
//以下是点击了index.jsp页面超链接生成的
request对象创建了 ......
request域修改了属性(这里展示的是被替换的):org.apache.catalina.ASYNC_SUPPORTED=true
request域添加了属性:a=aaaa
request域修改了属性(这里展示的是被替换的):a=aaaa
request域删除了属性:a=bbbb
request对象销毁了 ......