2017-06-01 31 views

回答

1

ServletContextListener

你的意思是“部署”到底是什么意思?

如果您的意思是在servlet容器在运行时为您的Web应用程序创建上下文,那么在第一个请求被您的servlet处理之前,请使用标准挂钩来调用您的代码时刻。

创建一个实现ServletContextListener的类,使用所需的方法contextInitialized。在部署期间用@WebListener标注此信号。搜索堆栈溢出许多现有的问题&关于这个主题的答案,包括一些更长的答案由我。

在该方法中,捕获当前时刻为Instant,即时间轴上UTC的时间,分辨率为纳秒。

Instant instant = Instant.now() ; 

示例代码。

@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) { 
     … 
    } 

} 
0

您可以在应用程序的初始化阶段使用WAR文件的last modification time初始化该变量。

或者,使用诸如Maven之类的工具,然后将部署日期设置为项目属性是比上述方法更好的方法,因为WAR文件的路径可能会更改。