我正在向我的所有页面中动态注入一些JS,在Mojarra中可以正常工作,但是我发现它在我的脸上失败了。
我的事件侦听器配置为:
<application>
<system-event-listener>
<system-event-listener-class>a.b.HeadResourceListener</system-event-listener-class>
<system-event-class>javax.faces.event.PostAddToViewEvent</system-event-class>
<source-class>javax.faces.component.UIOutput</source-class>
</system-event-listener>
</application>
代码看起来像:
public class HeadResourceListener implements SystemEventListener {
@Override
public boolean isListenerForSource(Object source) {
return "javax.faces.Head".equals(((UIComponent) source).getRendererType());
}
@Override
public void processEvent(SystemEvent event) {
UIComponent outputScript = new UIOutput();
outputScript.setRendererType("javax.faces.resource.Script");
UIOutput content = new UIOutput();
content.setValue("var abc='';");
outputScript.getChildren().add(content);
context.getViewRoot().addComponentResource(context, outputScript, "head");
}
}
不幸的是,对于myfaces,源的rendererType永远不会是javax.faces.Head(我只发现了javax.faces.resources.Script和javax.faces.resources.Stylesheet的出现)
这里的行为有什么特殊的原因吗?对其他解决方案有什么建议吗?
编辑
根据建议,将此侦听器链接到源类时,它会在myfaces中触发。但是,在回发时,我得到重复的ID错误...
Caused by: org.apache.myfaces.view.facelets.compiler.DuplicateIdException: Component with duplicate id "j_id__v_7" found. The first component is {Component- Path : [Class: javax.faces.component.UIViewRoot,ViewId: /user/login.xhtml][Class: org.apache.myfaces.component.ComponentResourceContainer,Id: javax_faces_location_head][Class: javax.faces.component.UIOutput,Id: j_id__v_7]}
at org.apache.myfaces.view.facelets.compiler.CheckDuplicateIdFaceletUtils.createAndQueueException(CheckDuplicateIdFaceletUtils.java:148)
at [internal classes]
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:73)
at org.apache.myfaces.tomahawk.application.ResourceViewHandlerWrapper.renderView(ResourceViewHandlerWrapper.java:169)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:73)
表9-2
标准HTML RenderKit标记库