开发者

Accessing .properties file in webcontent folder form servlet project [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

I'm having some issues with loading a (.properties) file from the webcontent folder in my servlet. The solutions that I've found don't seem to work. I'm getting an exception when trying to read the file. Below my folder and package structure and the parts of code.

What am I doing wrong?

Webcontent folder structure

WebContent  
- WEB-INF  
- languages  
  -- language.properties  
- ....

Package structure

package x.y.z.aa  
- Servlet.java  
package x.y.z.ab  
- PropertyLoader.java  

Servlet.java code

public void init(ServletConfig config) throws ServletException {      
    super.init(config);  
    servletContext = this.getServletContext();  
    PropertyLoader = new PropertyLoader(servletContext);  
}

PropertyLoader.java

 public PropertyLoader(ServletContext context) {  
    super();  
    try{  
      properties.load(context.getResourceAsStream("/languages/language.properties"));  
      System.out.println(languages.get("test"));  
    } catch (Exception e){  
      System.out.println("Error reading properties file");  
      System.o开发者_JAVA百科ut.println(e.getMessage());  
    }
}

Sorry. I forgot to instantiate the Properties instance variable. Thanks for the tip regarding HTTP access when it's in its current location. This should be resolved when I put it under the WEB-INF Folder?


It is advisable to place such files in WEB-INF. Then the following should work, if the file is there (actually it should work in your current setup as well). Just make sure the file is well-formed - i.e. that it is a real properties file.

properties.load(context
    .getResourceAsStream("/WEB-INF/languages/language.properties"));


You should think about changing your properties file location. At the current location it's contents can be accesed through a simple HTTP GET request (as in http://host:8080/AppContext/languages/language.properties ), which could be considered as a security issue.

Also, if you could post the exception you get, could be from more help to find what's happening with your code.


Yes, usually you put things like this in the WEB-INF folder. Unless you really want it to be accessible via HTTP for some reason.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜