替代ServletRequestListener中的requestDestroyed

问题描述 投票:1回答:1

正在将requestDestroyed方法编写为servlet本身的一部分,就像下面在功能上等同于将requestDestroyed重写为ServletRequestListener的一部分一样吗?

public class MyServlet implements HttpServlet{

   public void init(ServletConfig config) throws ServletException {
       //init stuff
   }

   public void service(ServletRequest req,ServletResponse res) 
   throws ServletException {
       try {
          //do some stuff
       } finally {
          requestDestroyed(request);
       }
   }

   private void requestDestroyed(HttpServletRequest request) {
      //some clean up stuff only for this particular servlet
   }
}
java servlets jakarta-ee
1个回答
0
投票

答案:不,这不是等效的。

有两个选项:

第一个选项:

要覆盖requestDestroyed方法,您需要在自定义侦听器类中实现ServletRequestListener

例如:

我创建了一个RListener类作为自定义侦听器:

public class RListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
      HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequestEvent.getServletRequest();
      System.out.println("All resources has been destroyed.") 
      //some clean up stuff only for this particular servlet
    }

    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequestEvent.getServletRequest();
        System.out.println("All resources has been initalized.") 
       //some initialization up stuff only for this particular servlet
    }
}

在web.xml中添加<listener>

<listener>
    <listener-class>com.example.RListener</listener-class>
</listener>

第二个选项:

您可以覆盖销毁方法,它是Servlet的生命周期方法:

示例:

public class MyServlet implements HttpServlet{

   @Override
   public void init(ServletConfig config) throws ServletException {
       //init stuff
   }

   @Override
   public void service(ServletRequest request, ServletResponse response)
   throws ServletException {
      try{
         //do some stuff
      }finally{
         destroy();
      }   
   }

   @Override
   public void destroy() { 
      //some clean up stuff only for this particular servlet
   } 

}
© www.soinside.com 2019 - 2024. All rights reserved.