我需要包括从file.properties
一些值到WEB-INF/web.xml
是这样的:如何将.properties文件中的值包含到web.xml中?
<param-name>uploadDirectory</param-name>
<param-value>myFile.properties['keyForTheValue']</param-value>
我目前这个工作:
- JBoss的
- JEE5
我需要包括从file.properties
一些值到WEB-INF/web.xml
是这样的:如何将.properties文件中的值包含到web.xml中?
<param-name>uploadDirectory</param-name>
<param-value>myFile.properties['keyForTheValue']</param-value>
我目前这个工作:
您可以添加此类,将文件中的所有属性添加到JVM。这个类像上下文监听器添加到web.xml
public class InitVariables implements ServletContextListener
{
@Override
public void contextDestroyed(final ServletContextEvent event)
{
}
@Override
public void contextInitialized(final ServletContextEvent event)
{
final String props = "/file.properties";
final Properties propsFromFile = new Properties();
try
{
propsFromFile.load(getClass().getResourceAsStream(props));
}
catch (final IOException e)
{
// can't get resource
}
for (String prop : propsFromFile.stringPropertyNames())
{
if (System.getProperty(prop) == null)
{
System.setProperty(prop, propsFromFile.getProperty(prop));
}
}
}
}
在web.xml
<listener>
<listener-class>
com.company.InitVariables
</listener-class>
</listener>
现在你可以得到所有的属性在你的项目中使用
System.getProperty(...)
或在web.xml
<param-name>param-name</param-name>
<param-value>${param-name}</param-value>
谢谢,这是我一直在寻找 – lancha90
我不能溶液没有让Jetty使用相对路径和getResourceAsStream找到资源,但绝对路径和FileInputStream似乎工作... +1让我朝着正确的方向发展! – jsh
这有没有实用工具? – user447607
使用Ant的replacetoken任务。 https://blogs.oracle.com/rajeshthekkadath/entry/automation_using_ant_replace_function
关于上述接受的解决方案,请注意谨慎。
我今天在jboss 5上做了这个试验:contextInitialized()
方法直到加载了web.xml
之后才会被调用,所以对系统属性的改变不会及时生效。奇怪的是,这意味着如果您重新部署webapp(不重新启动jboss),则该属性将从最后一次部署时的设置中存活下来,因此它可能会工作。
我们将要使用的解决方案是通过java命令行将参数传递给jboss,例如, -Dparameter1=value1 -Dparameter2=value2
。
更好的解决方案(虽然不能与jboss 7一起工作)是使用properties.service.xml。您可以在那里映射属性。 – gebuh
这是一个很好的想法(这是我们的系统管理员更喜欢保留系统属性的地方),但是你有这个工作吗?我尝试更新'server/default/deploy'和'server/all/deploy'下的properties.services.xml,无论哪种情况,它都不会在web.xml中生效 – dannyclark
[在web.xml使用属性]的可能的复制(http://stackoverflow.com/questions/2948992/using-properties-in-web-xml) – imgx64