java 如何在 JSF 应用程序中引用文件资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1528201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reference file resource in a JSF Application
提问by Daniel Szalay
I want to dynamically reference an XSD from a bean, how is this possible? I already added the XSD to the project, so it's located somewhere in the GlassFish domain.
我想从 bean 动态引用 XSD,这怎么可能?我已经将 XSD 添加到项目中,因此它位于 GlassFish 域中的某个位置。
回答by McDowell
Use the ExternalContext.
使用ExternalContext.
If you want to load the resource in the bean, do it via getResourceor getResourceAsStream:
如果要在 bean 中加载资源,请通过getResource或getResourceAsStream 执行:
InputStream stream = FacesContext.getCurrentInstance().getExternalContext()
.getResourceAsStream("/foo.xsd");
If you want to return a URL to the resource, use getRequestContextPathto get the path relative to the host root:
如果要返回资源的 URL,请使用getRequestContextPath获取相对于主机根目录的路径:
ExternalContext ext = FacesContext.getCurrentInstance()
.getExternalContext();
String path = ext.getRequestContextPath();
path += path.endsWith("/") ? "foo.xsd" : "/foo.xsd";
String url = ext.encodeResourceURL(path);

