02 ServletRequest相关监听器

ServletRequestListener
用于ServletReuqest对象(request请求对象)的创建和销毁行为。
创建:用户每次发出请求的时候都会创建一个请求对象
销毁:完成整个请求之后请求对象销毁

ServletRequestAttributeListener
用于监听ServletRequest对象的属性增加,修改,删除
增加: setAttribute("name",Object);
修改: setAttribute("name",Object); //把同名的属性进行修改
删除: removeAttribute("name");

  1. xml中配置
    
    
        
        com.xxjqr.servlet_study.listener.MyRequestListener 
    
  1. 代码如下
/**
 * ServetRequest的监听器
 *
 */
public class MyRequestListener implements ServletRequestListener,ServletRequestAttributeListener{

    /**
     * 用于监听request对象的创建
     */
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("一个请求对象被创建了");
        
        //得到请求对象相关的信息
        HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
        //得到客户的ip地址
        String ip = request.getRemoteHost();
        //共享数据到页面
        //HttpSession session = request.getSession(true);
        //session.setAttribute("ip", ip);
    }
    /**
     * 用于监听request对象的销毁
     */
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("一个请求对象被销毁了");
    }
    
    /***************属性相关***************/
    public void attributeAdded(ServletRequestAttributeEvent srae) {
        String name = srae.getName();
        Object value = srae.getValue();
        System.out.println("属性增加:"+name+"="+value);
    }
    public void attributeReplaced(ServletRequestAttributeEvent srae) {
        String name = srae.getName();
        ServletRequest request = srae.getServletRequest();
        Object value = request.getAttribute(name);
        System.out.println("属性修改:"+name+"="+value);
    }
    public void attributeRemoved(ServletRequestAttributeEvent srae) {
        String name = srae.getName();
        Object value = srae.getValue();
        System.out.println("属性删除:"+name+"="+value);
    }
    
}

你可能感兴趣的:(02 ServletRequest相关监听器)