2017-06-01 29 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文件的路徑可能會更改。