Search code examples
javaglassfishwarstruts-1

How to get the deployment date of a WAR file into Java code?


We are using Struts1.2 and Hibernate for our ERP. Suppose there is a Java class which is having an attribute called deploymentDate into which I have to store the date in which WAR file has been deployed, what should we do? We are using Glassfish 2.1 server.


Solution

  • ServletContextListener

    What do you mean by “deployed” exactly?

    If you mean when the servlet container is, at runtime, creating the context for your web app, before the first request has been handled by your servlet(s), use the standard hook for your code to be called at that moment.

    Create a class that implements ServletContextListener, with a required method contextInitialized. Annotate with @WebListener to signal this class during deployment. Search Stack Overflow for many existing Questions & Answers on this topic, including some longer Answers by me.

    In that method, capture the current moment as an Instant, a moment on the timeline in UTC with a resolution of nanoseconds.

    Instant instant = Instant.now() ;
    

    Example code.

    @WebListener
    public class MyServletContextListener implements ServletContextListener {
    
        public void contextInitialized( ServletContextEvent sce ) {
            Instant instant = Instant.now() ;  // Capture current moment in UTC.
            // By default `toString` generates string in standard ISO 8601 format. 
            // Easy to parse: Instant.parse( "2017-01-23T01:23:45.123456789Z" );
            String instantIso8601 = instant.toString() ;  
    
            // Remember the launch time as an attribute on the context.
            sce.getServletContext().setAttribute( "launch_instant" , instantIso8601 ) ;
            // Or save your moment in some class variable mentioned in Question.
            someObjectOfSomeClass.setLaunchInstant( instant );
        }
    
        public void contextDestroyed( ServletContextEvent sce ) {
            …
        }
    
    }