认识Requet域监听器
Requet域共有两个监听器接口,分别是
ServletRequestListener
ServleRequestAttributeListener
接下来我们就认识一些每个接口和接口中每个方法的用处
定义监听器类
package com.msb.listener;
import javax.servlet.*;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
public class MyRequestListener implements ServletRequestListener, ServletRequestAttributeListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
// 监听HttpServletRequest对象的销毁 项目中任何一个Request对象的销毁都会触发该方法的执行
ServletRequest servletRequest = sre.getServletRequest();
System.out.println("request"+servletRequest.hashCode()+"对象销毁了");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
// 监听HttpServletRequest对象的创建并初始化 项目中任何一个Request对象的创建并初始化都会触发该方法的执行
ServletRequest servletRequest = sre.getServletRequest();
System.out.println("request"+servletRequest.hashCode()+"对象初始化");
}
@Override
public void attributeAdded(ServletRequestAttributeEvent srae) {
// 任何一个Request对象中调用 setAttribute方法增加了数据都会触发该方法
ServletRequest servletRequest = srae.getServletRequest();
String name = srae.getName();
Object value = srae.getValue();
System.out.println("request"+servletRequest.hashCode()+"对象增加了数据:"+name+"="+value);
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent srae) {
// 任何一个Request对象中调用 removeAttribute方法移除了数据都会触发该方法
ServletRequest servletRequest = srae.getServletRequest();
String name = srae.getName();
Object value = srae.getValue();
System.out.println("request"+servletRequest.hashCode()+"对象删除了数据:"+name+"="+value);
}
@Override
public void attributeReplaced(ServletRequestAttributeEvent srae) {
// 任何一个Request对象中调用 setAttribute方法修改了数据都会触发该方法
ServletRequest servletRequest = srae.getServletRequest();
String name = srae.getName();
Object value = srae.getValue();
Object newValue=servletRequest.getAttribute(name);
System.out.println("request"+servletRequest.hashCode()+"对象增修改了数据:"+name+"="+value+"设置为:"+newValue);
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/6755736789dda01b81c557b37ed37805.png)
配置监听器 使用web.xml 或者通过@WebListener注解都可以
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<listener>
<listener-class>com.msb.listener.MyRequestListener</listener-class>
</listener>
</web-app>
![](https://i-blog.csdnimg.cn/blog_migrate/f7ece03c5048392bd48e53a9accc5f70.png)
![](https://i-blog.csdnimg.cn/blog_migrate/fa3bb106b9ea0edc62569668ae791103.png)
准备Servlet
@WebServlet(urlPatterns = "/myServlet3.do")
public class MyServlet3 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("name", "zhangsan");
req.setAttribute("name", "lisi");
req.removeAttribute("name");
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/550b644e68c2075c5cb79be955d6c789.png)