13

JSF 2 で複合コンポーネントをプログラムで作成する必要があります。数日間の検索と実験の後、この方法を見つけました (java.net の Lexi に大いに触発されました)。

/**
 * Method will attach composite component to provided component
 * @param viewPanel parent component of newly created composite component
 */
public void setComponentJ(UIComponent viewPanel) {
    FacesContext context = FacesContext.getCurrentInstance();
    viewPanel.getChildren().clear();

    // load composite component from file
    Resource componentResource = context.getApplication().getResourceHandler().createResource("whatever.xhtml", "components/form");
    UIComponent composite = context.getApplication().createComponent(context, componentResource);

    // push component to el
    composite.pushComponentToEL(context, composite);
    boolean compcompPushed = false;
    CompositeComponentStackManager ccStackManager = CompositeComponentStackManager.getManager(context);
    compcompPushed = ccStackManager.push(composite, CompositeComponentStackManager.StackType.TreeCreation);

    // Populate the component with value expressions 
    Application application = context.getApplication();
    composite.setValueExpression("value", application.getExpressionFactory().createValueExpression(
            context.getELContext(), "#{stringValue.value}",
            String.class));

    // Populate the component with facets and child components (Optional)
    UIOutput foo = (UIOutput) application.createComponent(HtmlOutputText.COMPONENT_TYPE);
    foo.setValue("Foo");
    composite.getFacets().put("foo", foo);
    UIOutput bar = (UIOutput) application.createComponent(HtmlOutputText.COMPONENT_TYPE);
    bar.setValue("Bar");
    composite.getChildren().add(bar);

    // create composite components Root
    UIComponent compositeRoot = context.getApplication().createComponent(UIPanel.COMPONENT_TYPE);
    composite.getAttributes().put(Resource.COMPONENT_RESOURCE_KEY, componentResource);
    compositeRoot.setRendererType("javax.faces.Group");
    composite.setId("compositeID");

    try {
        FaceletFactory factory = (FaceletFactory) RequestStateManager.get(context, RequestStateManager.FACELET_FACTORY);
        Facelet f = factory.getFacelet(componentResource.getURL());
        f.apply(context, compositeRoot); //<==[here]
    } catch (Exception e) {
        log.debug("Error creating composite component!!", e);
    }
    composite.getFacets().put(
            UIComponent.COMPOSITE_FACET_NAME, compositeRoot);

    // attach composite component to parent componet
    viewPanel.getChildren().add(composite);

    // pop component from el
    composite.popComponentFromEL(context);
    if (compcompPushed) {
        ccStackManager.pop(CompositeComponentStackManager.StackType.TreeCreation);
    }
}

問題は、このコードjavax.faces.PROJECT_STAGEが に設定されている場合にのみ機能することですPRODUCTION(これを理解するのに一日中かかりました)。javax.faces.PROJECT_STAGEが設定されている場合DEVELOPMENT、マークされたポイントで例外がスローされます ( <==[here]):

javax.faces.view.facelets.TagException: /resources/components/form/pokus.xhtml @8,19 <cc:interface> Component Not Found for identifier: j_id2.getParent().  
    at com.sun.faces.facelets.tag.composite.InterfaceHandler.validateComponent(InterfaceHandler.java:135)  
    at com.sun.faces.facelets.tag.composite.InterfaceHandler.apply(InterfaceHandler.java:125)  
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:98)  
    at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)  
    at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:82)  
    at com.sun.faces.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:152)  
    at cz.boza.formcreator.formcore.Try.setComponentJ(Try.java:83)  
    at cz.boza.formcreator.formcore.FormCreator.<init>(FormCreator.java:40)  
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)  
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)  
    at java.lang.reflect.Constructor.newInstance(Constructor.java:532)  

compositeRootコンポーネント (j_id2の自動生成 ID ) に設定された親に問題がありますcompositeRoot。また、このコードは十分にテストされていないため、信頼できるかどうかわかりません。

複合コンポーネントをプログラムで操作できることは非常に重要だと思います。そうでなければ、複合コンポーネントは半分役に立ちません。

4

2 に答える 2

18

具体的な問題を詳しく説明することはできませんが、質問に示されているアプローチがぎこちなく、Mojarra と密結合していることを観察して確認することしかできません。com.sun.faces.*Mojarra を必要とする特定の依存関係があります。このアプローチは標準の API メソッドを利用していないため、MyFaces などの他の JSF 実装では機能しません。

これは、標準の API 提供のメソッドを利用した、はるかに単純なアプローチです。重要な点はFaceletContext#includeFacelet()、特定の親に複合コンポーネント リソースを含めるために使用する必要があるということです。

public static void includeCompositeComponent(UIComponent parent, String libraryName, String resourceName, String id) {
    // Prepare.
    FacesContext context = FacesContext.getCurrentInstance();
    Application application = context.getApplication();
    FaceletContext faceletContext = (FaceletContext) context.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);

    // This basically creates <ui:component> based on <composite:interface>.
    Resource resource = application.getResourceHandler().createResource(resourceName, libraryName);
    UIComponent composite = application.createComponent(context, resource);
    composite.setId(id); // Mandatory for the case composite is part of UIForm! Otherwise JSF can't find inputs.

    // This basically creates <composite:implementation>.
    UIComponent implementation = application.createComponent(UIPanel.COMPONENT_TYPE);
    implementation.setRendererType("javax.faces.Group");
    composite.getFacets().put(UIComponent.COMPOSITE_FACET_NAME, implementation);

    // Now include the composite component file in the given parent.
    parent.getChildren().add(composite);
    parent.pushComponentToEL(context, composite); // This makes #{cc} available.
    try {
        faceletContext.includeFacelet(implementation, resource.getURL());
    } catch (IOException e) {
        throw new FacesException(e);
    } finally {
        parent.popComponentFromEL(context);
    }
}

<my:testComposite id="someId">from URIを含めたいと想像してxmlns:my="http://java.sun.com/jsf/composite/mycomponents"、次のように使用します。

includeCompositeComponent(parent, "mycomponents", "testComposite.xhtml", "someId");

これは、JSF ユーティリティ ライブラリOmniFacesにも追加されましたComponents#includeCompositeComponent()(V1.5 以降)。


JSF 2.2 以降の更新では、この目的にも使用できる taglib URI とタグ名をViewDeclarationLanguage取得する新しいメソッドがクラスに追加されました。createComponent()したがって、JSF 2.2 を使用している場合、アプローチは次のように行う必要があります。

public static void includeCompositeComponent(UIComponent parent, String taglibURI, String tagName, String id) {
    FacesContext context = FacesContext.getCurrentInstance();
    UIComponent composite = context.getApplication().getViewHandler()
        .getViewDeclarationLanguage(context, context.getViewRoot().getViewId())
        .createComponent(context, taglibURI, tagName, null);
    composite.setId(id);
    parent.getChildren().add(composite);
}

<my:testComposite id="someId">from URIを含めたいと想像してxmlns:my="http://xmlns.jcp.org/jsf/composite/mycomponents"、次のように使用します。

includeCompositeComponent(parent, "http://xmlns.jcp.org/jsf/composite/mycomponents", "testComposite", "someId");
于 2013-04-08T16:44:50.093 に答える
7

どちらのソリューションもうまくいかなかったので、JSF 実装を調べて、静的に挿入されたコンポジットがどのように追加され、コンポーネント ツリーで処理されるかを調べました。これは私が最終的に終わった作業コードです:

public UIComponent addWidget( UIComponent parent, String widget ) {
    UIComponent cc = null;
    UIComponent facetComponent = null;
    FacesContext ctx = FacesContext.getCurrentInstance();
    Resource resource = ctx.getApplication().getResourceHandler().createResource( widget + ".xhtml", "widgets" );
    FaceletFactory faceletFactory = (FaceletFactory) RequestStateManager.get( ctx, RequestStateManager.FACELET_FACTORY );

    // create the facelet component
    cc = ctx.getApplication().createComponent( ctx, resource );

    // create the component to be populated by the facelet
    facetComponent = ctx.getApplication().createComponent( UIPanel.COMPONENT_TYPE );
    facetComponent.setRendererType( "javax.faces.Group" );

    // set the facelet's parent
    cc.getFacets().put( UIComponent.COMPOSITE_FACET_NAME, facetComponent );

    // populate the facetComponent
    try {
        Facelet facelet = faceletFactory.getFacelet( resource.getURL() );
        facelet.apply( ctx, facetComponent );
    } catch ( IOException e ) {
        e.printStackTrace();
    }

    // finally add the facetComponent to the given parent
    parent.getChildren().add( cc );

    return cc;
}
于 2012-11-16T09:52:28.123 に答える