在JSF中从Managed Bean获取资源文件的路径 [英] Getting a path to a resource file from managed-bean in JSF

查看:163
本文介绍了在JSF中从Managed Bean获取资源文件的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况:在尝试从托管bean放置新的头像图像之前,我正在尝试为用户删除旧的头像图像.

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);

我已经用Google搜索了一下,看来我可以从ExternalContext获取到该文件夹​​的路径,例如:

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.我怀疑以某种方式可以对链接进行硬编码,但到目前为止还算不上运气.

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

推荐答案

我了解该文件已嵌入WAR中,并且您正在寻找而是ServletContext#getRealPath() (这也是新JSF 2.0方法委派给的内容).

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);
// ...

但是,有一个很大的 BUT :您可以并且不应该对扩展的WAR进行写入.删除文件也在写.每当您重新部署WAR或重新启动服务器时,所有更改都会还原,并且扩展的WAR将保留其初始状态,从而丢失自上次部署以来在扩展的WAR中所做的所有更改.

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.

您确实需要将这些文件存储在外部位置,然后可以在某些外部配置(属性)文件中对其根位置进行硬编码或定义.这样,您可以按常规方式使用java.io.File内容.

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.

有几种方法可以从外部位置提供文件.您可以在以下问题的答案中找到所有内容:加载使用< h:graphicImage>来自webapps/webcontext/deploy文件夹外部的图像或< img>标签

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

这篇关于在JSF中从Managed Bean获取资源文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆