gpt4 book ai didi

jsf-2 - 在 JSF2.0 中读取属性文件也可以在 war 中工作

转载 作者:行者123 更新时间:2023-12-02 06:37:08 25 4
gpt4 key购买 nike

要使用 Glassfishv3 网络服务器读取 JSF2.0 中的 properties 文件,该文件位于我的网络应用程序的 root 目录,我使用以下代码-

    ServletContext ctx = (ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext();
String deploymentDirectoryPath = ctx.getRealPath("/");
Properties prop = new Properties();
prop.load(new FileInputStream(deploymentDirectoryPath
+ File.separator + "portal-config.properties"));

下面是门户网站的截图-

enter image description here

运行门户时我收到 FileNotFound 错误,因为该文件不存在于 glassfish 域中。

有没有什么方法可以读取在开发阶段和 war 文件中都可以工作的属性文件?

最佳答案

永远不要使用 java.io.File 来引用网络资源。它对它所在的上下文一无所知。您也不应该使用 ServletContext#getRealPath(),因为当服务器配置为在中展开 WAR 文件时,它可能会返回 null内存而不是磁盘,这在第 3 方主机中是您无法控制的。

只需使用 ExternalContext#getResourceAsStream()InputStream 的形式直接获取 Web 资源。它采用相对于网络内容根目录的路径。

ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
properties.load(ec.getResourceAsStream("/portal-config.properties"));

另见:


更新 好像根本就不是网页资源。您应该将文件移动到“WebContent”文件夹中,如屏幕截图所示。或者,更好的是 /WEB-INF 文件夹,这样任何人都无法通过 URL 访问它。

properties.load(ec.getResourceAsStream("/WEB-INF/portal-config.properties"));

另一种方法是将它放在类路径中,如屏幕截图所示的“Java 源”文件夹中。你不需要把它放在一个包里,那是可选的。假设你没有把它放在一个包里,那么这样做:

ClassLoader cl = Thread.currentThread().getContextClassLoader();
properties.load(cl.getResourceAsStream("portal-config.properties"));

(注意路径不能以斜杠开头!)

关于jsf-2 - 在 JSF2.0 中读取属性文件也可以在 war 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15972175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com