如何在JSF应用程序中引用文件资源

问题描述:

我想从一个bean动态引用XSD,这可能如何?我已经将XSD添加到项目中,因此它位于GlassFish域中的某处。如何在JSF应用程序中引用文件资源

使用ExternalContext

如果要加载Bean中的资源,通过getResourcegetResourceAsStream做到这一点:

InputStream stream = FacesContext.getCurrentInstance().getExternalContext() 
    .getResourceAsStream("/foo.xsd"); 

如果你想要一个URL返回到资源,使用getRequestContextPath相对于主机的路径获得根:

ExternalContext ext = FacesContext.getCurrentInstance() 
    .getExternalContext(); 
String path = ext.getRequestContextPath(); 
path += path.endsWith("/") ? "foo.xsd" : "/foo.xsd"; 
String url = ext.encodeResourceURL(path); 
+0

非常感谢!我已经把它作为一个InputStream,然后我可以通过BufferedReader-InputStreamReader组合来读取XSD。 – 2009-10-07 21:24:22