|
|
Load Resources On J2 E E Web Applications
by FabrizioGianneschi, September 2003
published on http://www.programmazione.it A frequent problem in the development of J2EE web applications turns out to be the loading of resources (text files, images, ...) from Servlets, JSP or others web components. A typical error is to locate them through absolute paths (or references), making assumptions on the Web containerÂ’s folders structure. This is a wrong method, since it creates an high coupling between the application and the system. As an example, the following is a wrong approach to a resource:
In real cases, where possible, it is much better that an application references exclusively its resources, through relative paths. This should be made for many reasons: system-independent code increases the application portability and security, in the case the same application must be used in different containers or systems. Supposing to have to work with a Servlet, a correct method in order to load resources is the following: 1) in the web.xml, provide a servlet parameter containing the relative path of the resource that you want to load. This operation is not necessary, but strongly advised to increase decoupling between the resources and the code, not being forced to hard-code them. As an example: Listing 1 - Specification of the resource path in the web.xml
Note the attribute <param-value>: absolutely you should not write path pointing outside the Web application, but only relative to its content. In fact, the "/" before “WEB-INF” it is the root of your Web application (Context Root). It’s a bad practice to use: - the Web application name, because it could change at deployment time; - the deploy folder name, because the Servlet Specification doesn’t mandate it. Moreover, the webapp could be located in a different folder, which could be different on various container (Tomcat uses webapps). 2) Within the the servlet’s code, as an example, load the parameter in the init() method: Listing 2 - Loading the resource path parameter from the init() method of a Servlet
3) Use the path parameter in order to obtain the resource from the ServletContext (which delegates to the Servlet Container). You can take a java.net.URL or a java.io.InputStream instance from which reading. These are two practical examples: Listing 3 – Loading a Properties file
Listing 4 - Loading an XML file to a DOM object
|