Is there any method or API that I can use so that whenever I deploy a new WAR file, a part of code should execute or perhaps when Tomcat starts, the respective servlet should s
i find a way to run some code only at application (*.war) deployment: it works at least for jersey servlets with java servlet using javax.ws.rs.core.Application .
The application in the file ApplicationConfig.java (see below) contains a method public getClasses which is called at application deployment. So adding code in getClasses result in having it executed at application deployment. The only caveit i noticed is that strangely this function is called twice, do not know why ,so i added a global variable in the ApplicationConfig class to know if my code has already run.
Here is my solution:
package eu.oca;
import java.util.Set;
import javax.ws.rs.core.Application;
/**
*
* @author mattei
*/
@javax.ws.rs.ApplicationPath("jersey")
public class ApplicationConfig extends Application {
private boolean alreadyRun = false;
@Override
public Set> getClasses() {
System.out.println("Sidonie : ApplicationConfig : getClasses : alreadyRun = " + String.valueOf(alreadyRun));
alreadyRun = true;
Set> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method.
* It is automatically populated with
* all resources defined in the project.
* If required, comment out calling this method in getClasses().
*/
private void addRestResourceClasses(Set> resources) {
resources.add(eu.oca.ResultatGeneralAF.class);
resources.add(eu.oca.ResultatGeneralF.class);
resources.add(eu.oca.ResultatMesuresAF.class);
resources.add(eu.oca.ResultatMesuresF.class);
resources.add(eu.oca.SidonieAccueilD.class);
resources.add(eu.oca.SidonieWelcomeR.class);
}
}