如果您已经在 JSF 2.2 上,您可以通过提供一个自定义来做到这一点,您可以在ResourceHandler
其中返回所需的视图资源createViewResource()
。
public class FaceletsResourceHandler extends ResourceHandlerWrapper {
private ResourceHandler wrapped;
public FaceletsResourceHandler(ResourceHandler wrapped) {
this.wrapped = wrapped;
}
@Override
public ViewResource createViewResource(FacesContext context, final String name) {
ViewResource resource = super.createViewResource(context, name);
if (resource == null) {
resource = new ViewResource() {
@Override
public URL getURL() {
try {
return new File("/some/base/path", name).toURI().toURL();
} catch (MalformedURLException e) {
throw new FacesException(e);
}
}
};
}
return resource;
}
@Override
public ResourceHandler getWrapped() {
return wrapped;
}
}
注册faces-config.xml
如下:
<application>
<resource-handler>com.example.FaceletsResourceHandler</resource-handler>
</application>
或者,如果您还没有使用 JSF 2.2,那么请ResourceResolver
改用。
public class FaceletsResourceResolver extends ResourceResolver {
private ResourceResolver parent;
public FaceletsResourceResolver(ResourceResolver parent) {
this.parent = parent;
}
@Override
public URL resolveUrl(String path) {
URL url = parent.resolveUrl(path); // Resolves from WAR.
if (url == null) {
try {
url = new File("/some/base/path", path).toURI().toURL();
} catch (MalformedURLException e) {
throw new FacesException(e);
}
}
return url;
}
}
注册web.xml
如下:
<context-param>
<param-name>javax.faces.FACELETS_RESOURCE_RESOLVER</param-name>
<param-value>com.example.FaceletsResourceResolver</param-value>
</context-param>
无论采用哪种方式,为了从数据库中提供资源,您可以将它们保存/缓存在(临时)磁盘文件系统上,以便您可以提供URL
just via File
,或者发明一个自定义协议,例如db://
并提供一个自定义URLStreamHandlerFactory
和URLStreamHandler
实现从数据库执行流式传输的实际工作。您可以在此处找到启动示例Registering and using a custom java.net.URL protocol。