在应用程序启动时执行 servlet

yay*_*zis 4 java servlets

我用 JSP 构建了一个 Web 应用程序,在我的 servlet 中,我有:

public class MyServlet extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

           init();        
           HttpSession session = request.getSession(true);
           //more code...
    }
}
Run Code Online (Sandbox Code Playgroud)

直到现在我的 serlvet 被调用,当 JSP 页面像<a href="MyServlet..">. 我想要的是每当应用程序启动时,servlet 也会被执行。我可以在我的第一页有一个按钮,比如“开始”,然后在那里调用 servlet.. 但是,我可以避免这种情况吗?

Nic*_*ckJ 5

无论你想在启动时做什么,都应该由一个实现类来完成ServletContextListener,所以你应该写一个这样的类,例如:

public class MyContextListener 
           implements ServletContextListener{

  @Override
  public void contextDestroyed(ServletContextEvent arg0) {
    //do stuff
  }

  @Override
  public void contextInitialized(ServletContextEvent arg0) {
    //do stuff before web application is started
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你应该在 web.xml 中声明它:

<listener>
   <listener-class>
      com.whatever.MyContextListener 
   </listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)