代码之家  ›  专栏  ›  技术社区  ›  Ramps

自定义JSF组件,它向页面“head”方面添加了新的子项

  •  3
  • Ramps  · 技术社区  · 15 年前

    我想创建自定义组件,将新的子项添加到页面“head”方面。

    此自定义组件基于h:selectOneMenu。当在jsf页面上使用时,用户可以简单地更改当前主题。我需要这个组件做的是将样式表子项添加到head facet。

    我的组件支持java。我试图在encodeBegins()方法中修改“head”,但我的孩子根本没有被呈现。看看实施情况:

    
    
    @FacesComponent(value = "com.ramps.util.ThemeSelector")
    public class ThemeSelector extends UIInput implements NamingContainer {
    
     public void encodeBegin(FacesContext context) throws IOException {
    
       UIComponent headFacet = context.getViewRoot().getFacet("javax_faces_location_HEAD");     
       Resource res = new Resource();       
       res.setName("...");
       ...
       List <UIComponent> headChildren = headFacet.getChildren();
       headChildren.add(res);
    
       super.encodeBegin(context);
      }
     }
    

    是否可以直接从我的自定义组件的支持java修改“head”方面?如果是,我还缺什么?
    当做

    1 回复  |  直到 15 年前
        1
  •  4
  •   Sergio Castillo Diaz    9 年前

    UIViewRoot有一个方法将资源组件添加到 视图目标:

    public void addComponentResource(FacesContext上下文,UIComponent componentResource): 将假定表示资源实例的componentResource添加到当前视图中。资源实例由 资源呈现器(如ScriptRenderer、StylesheetRenderer)为 在标准的HTML RenderKit中描述。这种方法将导致 要在视图的head元素中呈现的资源。

    对于您的情况,组件是一个带有属性的UIOutput 名称 以及渲染类型 javax.faces.resource.Stylesheet .

    将自定义组件添加到视图后,可以添加样式表资源。这样做是为了注册它来监听PostAddToViewEvent。UIInput已经实现了ComponentSystemEventListener,所以必须重写processEvent。

    这是添加样式表的组件的工作示例。

    @FacesComponent("CustomComponent")
    @ListenerFor(systemEventClass=PostAddToViewEvent.class)
    public class CustomComponent extends UIInput{
    
        @Override
        public void processEvent(ComponentSystemEvent event) throws AbortProcessingException {
            if(event instanceof PostAddToViewEvent){
                UIOutput resource=new UIOutput();
                resource.getAttributes().put("name", "theme.css");
                resource.setRendererType("javax.faces.resource.Stylesheet");
                FacesContext.getCurrentInstance().getViewRoot().addComponentResource(FacesContext.getCurrentInstance(), resource);
            }
            super.processEvent(event);
        }
    
    }
    

    我想知道对于您正在尝试的工作来说,使用复合组件是否并不容易。

    推荐文章