如何将 WAR 文件的部署日期写入 Java 代码?
How to get the deployment date of a WAR file into Java code?
我们正在为我们的 ERP 使用 Struts1.2 和 Hibernate。假设有一个 Java class 有一个名为 deploymentDate
的属性,我必须在其中存储部署 WAR 文件的日期,我们应该怎么做?我们正在使用 Glassfish 2.1 服务器。
您可以在应用程序的初始化阶段使用 WAR 文件的 last modification time 初始化该变量。
或者,使用 Maven 之类的工具,然后将部署日期设置为项目 属性 是一种比上述方法更好的方法,作为 WAR 的路径文件可能会更改。
ServletContextListener
“部署”到底是什么意思?
如果你的意思是当 servlet 容器在运行时为你的 web 应用程序创建上下文时,在你的 servlet 处理第一个请求之前,使用标准钩子调用你的代码那一刻。
创建一个实现 ServletContextListener
, with a required method contextInitialized
的 class。使用 @WebListener
注释以在部署期间发出此 class 信号。在 Stack Overflow 中搜索有关此主题的许多现有问题和答案,包括我的一些更长的答案。
在该方法中,将当前时刻捕获为 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 ) {
…
}
}
我们正在为我们的 ERP 使用 Struts1.2 和 Hibernate。假设有一个 Java class 有一个名为 deploymentDate
的属性,我必须在其中存储部署 WAR 文件的日期,我们应该怎么做?我们正在使用 Glassfish 2.1 服务器。
您可以在应用程序的初始化阶段使用 WAR 文件的 last modification time 初始化该变量。
或者,使用 Maven 之类的工具,然后将部署日期设置为项目 属性 是一种比上述方法更好的方法,作为 WAR 的路径文件可能会更改。
ServletContextListener
“部署”到底是什么意思?
如果你的意思是当 servlet 容器在运行时为你的 web 应用程序创建上下文时,在你的 servlet 处理第一个请求之前,使用标准钩子调用你的代码那一刻。
创建一个实现 ServletContextListener
, with a required method contextInitialized
的 class。使用 @WebListener
注释以在部署期间发出此 class 信号。在 Stack Overflow 中搜索有关此主题的许多现有问题和答案,包括我的一些更长的答案。
在该方法中,将当前时刻捕获为 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 ) {
…
}
}