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

前端 未结 1 550
情歌与酒
情歌与酒 2020-12-21 11:28

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-

相关标签:
1条回答
  • 2020-12-21 12:26

    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!)

    0 讨论(0)
提交回复
热议问题