You*_*nes 6 javascript css jsf head
我需要以编程方式向<h:head>JSF页面添加JS和CSS资源.目前尚不清楚如何实现这一目标.有人可以给出提示或启动示例吗?
Bal*_*usC 12
这取决于你想要声明资源的确切位置.通常,以编程方式声明它们的唯一原因是您具有自定义UIComponent或Renderer生成HTML代码,而HTML代码又需要这些JS和/或CSS资源.然后他们将由@ResourceDependency或宣布@ResourceDependencies.
@ResourceDependency(library="mylibrary", name="foo.css")
public class FooComponentWithCSS extends UIComponentBase {
// ...
}
Run Code Online (Sandbox Code Playgroud)
@ResourceDependencies({
@ResourceDependency(library="mylibrary", name="bar.css"),
@ResourceDependency(library="mylibrary", name="bar.js")
})
public class BarComponentWithCSSandJS extends UIComponentBase {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是如果你真的需要在其他地方声明它们,比如在渲染响应之前调用的支持bean方法(否则它太迟了),那么你可以通过它来实现UIViewRoot#addComponentResource().必须将组件资源创建为UIOutput具有渲染器类型的javax.faces.resource.Scriptor 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");
Run Code Online (Sandbox Code Playgroud)