这取决于您到底想在哪里声明资源。 通常
,以编程方式声明它们的唯一原因是您拥有一个自定义
UIComponent或
Renderer生成HTML代码,而这些代码又需要这些JS和/或CSS资源。然后由
@ResourceDependency或声明它们
@ResourceDependencies。
@ResourceDependency(library="mylibrary", name="foo.css")public class FooComponentWithCSS extends UIComponentbase { // ...}@ResourceDependencies({ @ResourceDependency(library="mylibrary", name="bar.css"), @ResourceDependency(library="mylibrary", name="bar.js")})public class BarComponentWithCSSandJS extends UIComponentbase { // ...}但是,如果您 确实 需要在其他地方声明它们,例如 在 渲染响应 之前 调用的backing
bean方法(否则为时已晚),则可以使用
UIViewRoot#addComponentResource()。必须将组件资源创建为
UIOutput呈现器类型为
javax.faces.resource.script或
javax.faces.resource.Stylesheet,以分别表示完全值
<h:outputscript>或
<h:outputStylesheet>。该
library和
name属性正好可以放在属性地图。
UIOutput css = new UIOutput();css.setRendererType("javax.faces.resource.Stylesheet");css.getAttributes().put("library", "mylibrary");css.getAttributes().put("name", "bar.css");UIOutput js = new UIOutput();js.setRendererType("javax.faces.resource.script");js.getAttributes().put("library", "mylibrary");js.getAttributes().put("name", "bar.js");FacesContext context = FacesContext.getCurrentInstance();context.getViewRoot().addComponentResource(context, css, "head");context.getViewRoot().addComponentResource(context, js, "head");


