Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 521
Pavlo Bazilnskyy Avatar asked Jun 07 '11 20:06

Pavlo Bazilnskyy


1 Answers

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

like image 176
BalusC Avatar answered Oct 31 '22 17:10

BalusC