Java EE Enterprise Application: perform some action on deploy/startup [duplicate]

本秂侑毒 提交于 2019-11-26 14:29:48

问题


This question already has an answer here:

  • Using special auto start servlet to initialize on startup and share application data 1 answer

I would like to perform some action as soon as my application (Enterprise Application with Business Logic, EJB, and a Client, Web) is deployed. For example I would like to make some entity in a persistent state, or otherwise create a file. How can I do that?

Thanks.


回答1:


Configure SerlvetContextListener and override contextInitilized()

in your web application description , web.xml

<web-app ...>
    <listener>
        <listener-class>com.someCompany.AppNameServletContextListener</listener-class>
    </listener>
</web-app

package com.someCompany;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class AppNameServletContextListener implements ServletContextListener{

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("ServletContextListener destroyed");
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("ServletContextListener started");   
                // do the things here 
    }
}



回答2:


The "default" way is to have a servlet with an init() method. Then in the servlet-descriptor you mark this servlet as load-on-startup 1:

Example:

<servlet-name>Seam Resource Servlet</servlet-name>
   <servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

As soon as the servlet is deployed (which happens after the EJBs are deployed), that init() method is called and you can execute the task you want.




回答3:


With present web application in your ear, the easiest and simplest would be to use ServletContextListener, otherwise in EJB 3.1 you could use automatic timers or startup singleton session beans.



来源:https://stackoverflow.com/questions/6120831/java-ee-enterprise-application-perform-some-action-on-deploy-startup

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