ServletRequestListener的用法和实例

ServletRequestListener:
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
ServletRequestListener能监听到Request的生成和销毁。



例 2.2.5.1

package com;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class MyServletRequestListener implements
ServletRequestListener {
/*public void requestDestroyed(ServletRequestEvent sre)Notification that the servlet request is about to go out of scope. */
    public void requestDestroyed(ServletRequestEvent arg0) {
        System.out.println("马克-to-win destroyed"+arg0.getServletRequest().getRemoteAddr());
    }
/*public void requestInitialized(ServletRequestEvent sre)Notification that the servlet request is about to go into scope. */
    public void requestInitialized(ServletRequestEvent arg0) {
        System.out.println("马克-to-win request Initialized"+arg0.getServletRequest().getRemoteAddr());
    }
}


web.xml加入下面这段话:

  <listener>
    <listener-class>com.MyServletRequestListener</listener-class>
  </listener>







用下面这两个servlet测试:


package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ServletHello1 before");
        request.getRequestDispatcher("/ServletHello2").forward(request,response);
        System.out.println("这里会block5秒,ServletHello1 after");
    }
}




package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ServletHello2 extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("ServletHello2");
    }
}



运行这个ServletHello1以后,  (如果ip地址是ipv6,比如: 0:0:0:0:0:0:0:1则换成http://127.0.0.1:8080/Filter2251/MarkToWinServlet)   console里的输出结果是:

马克-to-win request Initialized127.0.0.1
ServletHello1 before
ServletHello2
这里会block5秒,ServletHello1 after
马克-to-win destroyed127.0.0.1