Saturday, March 9, 2013

How to get the path of the WEB-INF or any folder under it in Struts

You may have a folder for resources under the WEB-INF of your Struts application or even any Java web application. For example if you have a folder called "resources" which is under the WEB-INF and you would like to retrieve the absolute path so you can read or write on it. You can do this by:-

First: Get the ServletContext through the ServletActionContext.getServletContext().
ServletContext servletContext = ServletActionContext.getServletContext();

Second: Get the path of the WEB-INF or the "resources" folder.
//path of the Web Content
String path1 = servletContext.getRealPath("");
//path of the WEB-INF
String path2 = servletContext.getRealPath("/WEB-INF");
//path of the folder "resources" under the WEB-INF
String path3 = servletContext.getRealPath("/WEB-INF/resources");

The good thing is that the ServletContext is an interface in Java web API which means that there should be an implementation for this interface by all the vendors unless you are accessing a servlet on a remote system not on the local system of your application.

References:
1. Thanks to this post made by Hazem Saleh

No comments:

Post a Comment