Reading properties file in JSF2.0 which can work in war also

拜拜、爱过 提交于 2019-11-28 09:46:31

问题


To read a properties file in JSF2.0 with Glassfishv3 webserver, which is located at root directory of my web application, I am using below code-

    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"));

Below is the screenshot of web portal-

While running the portal I am getting FileNotFound Error, since the file is not present in glassfish domain.

Is there any way to read properties file which can work in both the situations, at development stage and in war file also?


回答1:


You should never use java.io.File to refer web resources. It knows nothing about the context it is sitting in. You should also never use ServletContext#getRealPath() as it may return null when the server is configured to expand WAR file in memory instead of on disk, which is beyond your control in 3rd party hosts.

Just use ExternalContext#getResourceAsStream() to get the web resource directly in flavor of an InputStream. It takes a path relative to the webcontent root.

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

See also:

  • getResourceAsStream() vs FileInputStream
  • What does servletcontext.getRealPath("/") mean and when should I use it
  • Where to place and how to read configuration resource files in servlet based application?

Update it does not seem to be a web resource at all. You should move the file into the "WebContent" folder as shown in the screenshot. Or, better, the /WEB-INF folder so that nobody can access it by URL.

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

An alternative would be to put it in the classpath, the "Java source" folder as shown in the screenshot. You don't need to put it in a package, that's optional. Assuming that you didn't put it in a package, then do so:

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

(note that the path may not start with a slash!)



来源:https://stackoverflow.com/questions/15972175/reading-properties-file-in-jsf2-0-which-can-work-in-war-also

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!