How to call a Java method while deploying a WAR [duplicate]

一笑奈何 提交于 2019-12-11 17:48:35

问题


How to call a Java method while deploying a WAR


回答1:


It's not clear what you mean by "deploy". Is that the moment when the WAR file arrives on the app server? Maybe you gin something up with Ant. Is that when the app starts up? Maybe you can do it with a ServletContextListener.

There's no mechanism for doing so built into any Java EE app server I know of, so you're out of luck if Ant isn't suitable. You need something that does the deploying to do it for you.

What's your purpose for doing so? What does this method do?




回答2:


Multiple solutions are available to you:

  • A ServletContextListener can be used to listen to startup events and execute appropriate actions.
  • The same thing can be done using a Servlet, with the load-on-startup attribute. You don't have to map your servlet to a servlet-path and can use it only for startup actions.
  • If you are using Java EE 6, you can use an EJB anotated with @Startup, which instanciate the service during startup. A @PostConstruct annotation declares a method to execute after instantiation. Note this works only with EJB singletons.



回答3:


You can use ServletContextListener




回答4:


If you want to put this functionality in you web app then right place is ServletContextListener

Implementations of the ServletContextListener interface receive notifications about changes to the servlet context of the Web application of which they are part. The following methods are defined in the ServletContextListener :

public void contextInitialized(ServletContextEvent sce)
public void contextDestroyed(ServletContextEvent sce)

The contextInitialized() method is invoked when the Web application is ready for service and the contextDestroyed() method is called when it is about to shut down. The following code shows how we can use these methods to log the application events:

public void contextInitialized(ServletContextEvent e) {
    e.getServletContext().log("Context initialized");
}

public void contextDestroyed(ServletContextEvent e) {
    e.getServletContext().log("Context destroyed");
}

see example, or you can extend you container/server to monitor, as same as monitor tools.



来源:https://stackoverflow.com/questions/6016143/how-to-call-a-java-method-while-deploying-a-war

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