问答详情
源自:3-3 ServletRequest的事件监听器

为什么我每次运行项目时request都initialize了三次

代码如下

```

public class FirstListener implements ServletRequestListener {

   // Public constructor is required by servlet spec
   public FirstListener() {
   }

@Override
   public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
       System.out.println("request destroyed initParam=" + servletRequestEvent.getServletContext().getAttribute("initParam"));
   }

   @Override
   public void requestInitialized(ServletRequestEvent servletRequestEvent) {
       servletRequestEvent.getServletContext().setAttribute("intiParam","yang");
       System.out.println("request initialized");
   }
}

```

运行结果

```

Connected to server

[2017-12-23 10:44:47,157] Artifact ListenerDemo:war exploded: Artifact is being deployed, please wait...

[2017-12-23 10:44:47,776] Artifact ListenerDemo:war exploded: Artifact is deployed successfully

[2017-12-23 10:44:47,776] Artifact ListenerDemo:war exploded: Deploy took 619 milliseconds

request initialized

request destroyed initParam=null

request initialized

request destroyed initParam=null

request initialized

request destroyed initParam=null

```

提问者:qq_何足道_1 2017-12-23 10:49

个回答

  • qq_何足道_1
    2017-12-23 10:50:14

    额,代码竟然不显示

    我再贴一下

    public class FirstListener implements ServletRequestListener {
    
       // Public constructor is required by servlet spec
       public FirstListener() {
       }
    @Override
       public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
           System.out.println("request destroyed initParam=" + servletRequestEvent.getServletContext().getAttribute("initParam"));
       }
    
       @Override
       public void requestInitialized(ServletRequestEvent servletRequestEvent) {
           servletRequestEvent.getServletContext().setAttribute("intiParam","yang");
           System.out.println("request initialized");
       }
    }