在运行时修改Tomcat中的属性文件 [英] modify properties file in Tomcat during runtime

查看:37
本文介绍了在运行时修改Tomcat中的属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行时修改 Portlet 的属性文件.portlet 部署在 Tomcat 7.0.23 中,属性文件位于/WEB-INF/classes/content"中,我可以通过下面显示的代码访问它.实际上,代码执行没有任何异常,只是新添加的Property并没有保存到properties文件中.

I would like to modify a properties file of a Portlet during runtime. The portlet is deployed in a Tomcat 7.0.23 and the properties file sits in "/WEB-INF/classes/content" from where I can access it via the code shown below. In fact, the code is executed without any exceptions but the newly added Property is not saved to the properties file.

String fileName = "MyProps.properties";
String relativePath = "/WEB-INF/classes/content/";
String fullPath = "c:/tomcat-7.0.23/webapps/my-portlet/WEB-INF/classes/content/";
try {
    String path = relativePath + fileName;
    InputStream in = getPortletContext().getResourceAsStream(path);
    Properties props = new Properties();
    props.load(in);
    props.setProperty("test", "test");
    File file = new File(fullPath + fileName));
    FileOutputStream out = new FileOutputStream(file);
    props.store(out, "");
} catch(Exception ex) { // error handling here}

添加新属性后,我可以验证

After adding the new Property, I could verify with

props.list(System.out);

它确实被添加了.context.xml 文件包含以下条目:

that it was added indeed. The context.xml file contains the following entries:

 antiJARLocking="true"
 antiResourceLocking="true"

这是在正在运行的 Tomcat 实例中添加/更改属性的正确方法还是我应该采用不同的方法?如果是后者,怎样才能做到最好?

Is this the right way to add/change Properties in a running Tomcat instance or should I take a different approach? If the latter, how could it be achieved best?

非常感谢您的回答!

推荐答案

您绝对应该不要依赖于能够更改已部署的 Web 应用程序中包含的文件.此时控制权已移交给容器,文件可能会被覆盖,甚至可能不可写.这也给应用程序部署者带来了负担,因为现在他们不能简单地清除爆炸的 WAR 文件夹(如果存在)并重新部署存档.

You should definitely not rely on ever being able to change a file contained in a deployed web app. Control has been handed over to the container at that point and the file may be overwritten, or it may not even be writable. It also puts a burden on the application deployer, because now they cannot simply blow away the exploded WAR folder (if one exists) and redeploy the archive.

作为您方法的替代方法,请考虑将属性文件放置在 Web 应用程序外部的位置.我见过成功使用的一种方法是:

As an alternative to your approach, consider placing the properties file in a location external to the web app. One approach I've seen used successfully is this:

  1. 确定运行时属性文件所在的众所周知"位置托管,或允许部署者通过井指定此位置已知财产.
  2. 尝试从此位置读取您的属性文件.如果确实如此不存在,从存储在其中的模板创建和初始化它您的申请.
  3. 将应用程序执行期间所做的所有更改保存到此外部属性文件.

通过这种设置,您永远不必担心无法写入文件,或者它会被容器覆盖.

With this setup you never have to worry about not being able to write the file, or of it getting overwritten by the container.

这篇关于在运行时修改Tomcat中的属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆