This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi, I am trying to get my servlet to load a properties file in the servlets init() method. However the servlet complains that it cannot find the file. Does anyone know what directory the file should be in please? I am running tomcat, my web app is in a directory called 'helpdesk'. Many thanks...
Try to change ur web.xml to look like this <servlet> <servlet-name>xyz</servlet-name> <servlet-class>xyzServlet</servlet-class> <init-param> <param-name>properties</param-name> <param-value>/WEB-INF/conf/helpdesk.properties</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
put ur properties file at web-inf\conf\ directory. Later in ur servlet u can read the init parameter like this. String filename = getServletContext().getInitParameter("properties");
The code below is from production code I have running at works fine. The object sc is the ServletContext.
As in the example above, put the name of the .properties file as a parameter. I am using a ServletContextListener, so my parameter must be a context parameter. However, you could easily use a servlet with a servlet parameter. Use the ServletContext.getResourceAsStream method as this allows the file to be found regardless of deploy type (.war or non-jar). Since this returns a stream and a properties object can load from a stream, it is a good match.
The usual problem people have is because relative file paths don't work in a servlet environment. However, it you use the Java Properties services, you can read the properties simply by naming them as though they were a Java class (which they might be anyway!). for example, "com.mywebsite.myapp.Global" is a valid name for the resource contained in the file "WEB-INF/classes/com/mywebsite/myapp/Global.properties".
An IDE is no substitute for an Intelligent Developer.
Joined: Jul 25, 2002
The example I have listed works. As stated, it is in a production environment. Using the method you have just listed seems to have limitations. I would suggest leveraging what the system is required to do and what the Properties object, by design, provides to you. While the getRealPath method has issues with getting a stream of a resource, I have never had an issue with getting a file using getResourceAsStream. Think about it, packages such as STRUTS and Log4J must be able to get to their config files, which are usually stored under the WEB-INF directory. A relative path is supposed to work in the current context. If it does not, I doubt the product would have passed J2EE certification.