Requet域监听器
一、认识Requet域监听器
Requet域共有两个监听器接口,分别是
ServletRequestListener
ServleRequestAttributeListener
接下来我们就认识一些每个接口和接口中每个方法的用处
二、定义监听器类
代码语言:javascript复制package com.lanson.listener;
import javax.servlet.*;
/**
* @Author: Lansonli
* @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);
}
}
三、配置监听器
使用web.xml 或者通过@WebListener注解都可以
代码语言:javascript复制<?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.lanson.listener.MyRequestListener</listener-class>
</listener>
</web-app>
四、准备Servlet
代码语言:javascript复制@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");
}
}