在JSF Managed Bean中检索Web应用程序的根路径 [英] Retrieve the web app root path in JSF Managed Bean

查看:85
本文介绍了在JSF Managed Bean中检索Web应用程序的根路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问jsf托管Bean中的 example/web 文件夹(见下图),但似乎找不到解决方法

Im trying to access the example/web folder (see below in the image) in a jsf managed bean but cant seem to find a way to do it

thx

推荐答案

如果出于某种原因要以File的形式获取它,则需要

If you want to get it as a File for some reason, then you need ExternalContext#getRealPath(). This converts a relative web path to an absolute disk file system. Since you need the web's root folder, just pass in /:

String absoluteWebPath = externalContext.getRealPath("/");
File webRoot = new File(absoluteWebPath);
// ...


无关与具体问题无关,无论您想到什么功能要求,都认为拥有到Web文件夹的绝对本地磁盘文件系统路径是正确的解决方案,它具有大多数绝对有待解决.确实,根据您对其他答案的评论,


Unrelated to the concrete problem, whatever functional requirement you've had in mind for which you thought that having an absolute local disk file system path to the web folder is the right solution, it has most definitely to be solved differently. And indeed, as per your comment on the other answer,

因为我试图在文件夹中上传一些文件并使用相对路径

您走错了路.如果您打算将上传的文件保留的时间长于Webapp的部署生命周期,则不应在其中存储这些文件.每当您重新部署Web应用程序时(甚至在重新启动服务器时,在某些服务器配置上也是如此),上载的文件将完全丢失,这仅仅是因为它们不包含在原始WAR文件中.更重要的是,一些繁琐的服务器配置根本不会在磁盘上扩展WAR,但是在内存中,getRealPath()总是会返回null.

you're going the wrong path. You should not store uploaded files in there if you intend to keep them longer than the webapp's deployment lifetime. Whenever you redeploy the webapp (and on some server configs even when you restart the server), the uploaded files would get completely lost, simply because they are not contained as part of the original WAR file. Even more, some heavy server configs don't expand the WAR on disk at all, but in memory instead, the getRealPath() would then always return null.

而是将其存储在服务器的deploy文件夹之外的固定磁盘文件系统路径中.依次将该路径添加为新的服务器上下文或docroot,以便可以在其他(虚拟)上下文路径上访问该路径.或本地增长一个servlet,该servlet从磁盘获取InputStream并将其写入响应的OutputStream中.另请参阅以下相关答案:上传的图片仅在刷新后可用页面

Rather store it in a fixed disk file system path outside the server's deploy folder. Add that path in turn as a new server context or docroot, so that it's accessible on a different (virtual) context path. Or homegrow a servlet which gets an InputStream of it from disk and writes it to OutputStream of the response. See also this related answer: Uploaded image only available after refreshing the page

这篇关于在JSF Managed Bean中检索Web应用程序的根路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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