Getting a path to a resource file from managed-bean in JSF

Pavlo Bazilnskyy picture Pavlo Bazilnskyy · Jun 7, 2011 · Viewed 29k times · Source

I have this situation: I am trying to remove an old avatar image for a user before putting a new one from the managed bean.

String fileName = "resources/img/useravatars/" + getSessionBean().getSearchAccount().getAvatar();
File f = new File(fileName);

I've googled a bit and it seems that I can get a path to that folder from ExternalContext like:

FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.getExternalContext(). ...

But I couldn't find an appropriate method from class docs. Could you please help with what to put instead of ... or suggest a better solution.

PS. Somehow, I suspect it is possible to hardcode the link, but no luck so far.

Answer

BalusC picture BalusC · Jun 7, 2011

I understand that the file is embedded in the WAR and that you're looking for the ExternalContext#getRealPath() method to resolve it based on a web-relative path. As per the Javadoc, this method is introduced in JSF 2.0 and does not exist in JSF 1.x. You seem to be using JSF 1.x, otherwise you wouldn't have asked this question. You need to use ServletContext#getRealPath() instead (which is also what the new JSF 2.0 method is delegating to, under the covers).

String relativeWebPath = "/resources/img/useravatars/" + ...;
ServletContext servletContext = (ServletContext) externalContext.getContext();
String absoluteDiskPath = servletContext.getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
// ...

However, there's a big BUT: you can and should not write to the expanded WAR. Deleting files is also writing. Whenever you redeploy the WAR or restart the server, every change will be reverted and the expanded WAR will retain its initial state, hereby losing all changes made in the expanded WAR since the last deploy.

You really need to store those files in an external location whose root location can then be hardcoded or definied in some external configuration (properties) file. This way you can use java.io.File stuff the usual way.

There are several ways to serve files from an external location. You can find them all in the answer of the following question: Load images from outside of webapps / webcontext / deploy folder using <h:graphicImage> or <img> tag