从 JSF 中的托管 bean 获取资源文件的路径
我遇到这种情况:我试图在从托管 bean 中放置新的头像图像之前删除用户的旧头像图像。
String fileName = "resources/img/useravatars/" + getSessionBean().getSearchAccount().getAvatar();
File f = new File(fileName);
我用谷歌搜索了一下,似乎我可以从ExternalContext获取该文件夹的路径,例如:
FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.getExternalContext(). ...
但我无法从 类文档。您能否帮忙解决该用什么来代替...或提出更好的解决方案。
附言。不知何故,我怀疑可以对链接进行硬编码,但到目前为止还没有运气。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道该文件嵌入在 WAR 中,并且您正在寻找
ExternalContext#getRealPath()
方法根据 Web 相对路径解析它。根据 Javadoc,该方法是在 JSF 2.0 中引入的,在 JSF 1.x 中不存在。您似乎正在使用 JSF 1.x,否则您不会问这个问题。您需要使用 相反,使用ServletContext#getRealPath()
(这也是新的 JSF 2.0 方法在幕后委托的内容)。然而,有一个重要的但是:您可以但不应该写入到扩展的WAR。删除文件也是写入。每当您重新部署 WAR 或重新启动服务器时,每个更改都将被还原,并且扩展的 WAR 将保留其初始状态,从而丢失自上次部署以来在扩展的 WAR 中所做的所有更改。
您确实需要将这些文件存储在外部位置,然后可以对其根位置进行硬编码或在某些外部配置(属性)文件中定义。这样您就可以按照通常的方式使用
java.io.File
内容。有多种方法可以从外部位置提供文件。您可以在以下问题的答案中找到它们: 加载使用来自 webapps/webcontext/deploy 文件夹外部的图像或 标签
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 useServletContext#getRealPath()
instead (which is also what the new JSF 2.0 method is delegating to, under the covers).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