How execute Listener class every time i receive requests on my servlet

泪湿孤枕 提交于 2021-02-16 13:47:13

问题


When receiving requests on my servlet, i would like execute one listener class which is related with, and which contains some instructions.

So i implement on myListener the interface ServletContextListener, like this:

public class MyContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("Context Created");
    }

}

On my web.xml :

  <servlet>
    <servlet-name>StartUp</servlet-name>
    <servlet-class>com.servlets.StartUp</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>StartUp</servlet-name>
    <url-pattern>/StartUp</url-pattern>
  </servlet-mapping>

  <listener>
    <listener-class>com.servlets.MyContextListener</listener-class>
  </listener>

So how can i execute my listener, when receiving requests on my StartUp servlet ?


回答1:


The ServletContextListener is designed to listen on initialization and destroy of ServletContext. In other words, it's only invoked on webapp's startup and shutdown respectively.

You need a ServletRequestListener instead:

@WebListener
public class MyRequestListener implements ServletRequestListener {

    @Override
    public void requestInitialized(ServletRequestEvent event) {
        System.out.println("Request initialized");
    }

    @Override
    public void requestDestroyed(ServletRequestEvent event) {
        System.out.println("Request destroyed");
    }

}

Or, perhaps just a simple servlet filter. The difference is that you can configure it to listen on specific URL patterns or specific servlets and even specifically forwarded, included and/or error'ed requests.

@WebFilter("/StartUp") // or @WebFilter(servletNames={"StartUp"})
public class StartUpServletFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        System.out.println("Before StartUp servlet is invoked");
        chain.doFilter(req, res);
        System.out.println("After StartUp servlet is invoked");
    }

    // Don't forget the init() and destroy() boilerplate.

}


来源:https://stackoverflow.com/questions/16112129/how-execute-listener-class-every-time-i-receive-requests-on-my-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!