如何将JSF复合组件属性设置为ManagedBean属性?

5

所以我创建了一个复合组件 FileAdder.xhtml

<composite:interface>
    <composite:attribute name="type" value="#{editoriCompositeController.typeString}"/>
</composite:interface>

<composite:implementation>
    <h:form>
        <p:editor id="editor" widgetVar="editorWidget" value="some text" width="600" />
    </h:form>
</composite:implementation>

然后我有一个EditoriCompositeController ManagedBean:

@ViewScoped
@ManagedBean
public class EditoriCompositeController {

    String typeString;

    public void setTypeString(String typeStringParameter) {
        this.typeString = typeStringParameter;
    }

    public String getTypeString() {
        return typeString;
    }

}

然后在我的fileattachmentsview.xhtml文件中,我使用了这个组件:

    <owncomponents:fileadder type="MEMO" />

但是这并没有将后备 bean 的 typeString 值设置为“MEMO”。它仍然为空,我用一个打印值的按钮进行了测试。
我该如何让后备 bean 获取我在组合组件的类型属性中设置为“MEMO”的 typeString 值?为什么它是 null 而不是“MEMO”?

我想制作一个可重用的编辑器组件,其中有一个“类型”属性用于组件,因为应用程序在多个位置都有编辑器,并且每个编辑器都应将不同类型的文档持久化到数据库中。我希望当组件被呈现时,支持bean会获取复合组件的“类型”属性的值作为其typeString属性的值,以便稍后持久化用户提交编辑器内容时使用。该组合还具有布尔属性,用于确定是否呈现某些按钮。 - Steve Waters
2个回答

7
你需要将目标bean/model作为另一个复合属性传递。然后你可以在复合内部使用<c:set>来设置它的属性。
<cc:interface>
    <cc:attribute name="bean" type="com.example.Bean" />
    <cc:attribute name="type" type="java.lang.String" />
</cc:interface>
<cc:implementation>
    <c:set target="#{cc.attrs.bean}" property="type" value="#{cc.attrs.type}" />
    <p:editor value="#{cc.attrs.bean.text}" />
</cc:implementation>    

使用方法:

public class Bean {

    private String text;
    private String type; // I suggest to make it an enum.

    // ...
}

<h:form>
    <your:composite bean="#{bean}" type="MEMO" />
    <p:commandButton action="#{bean.submit}" />
</h:form>

请注意,我将表单从组合组件中分离出来。在组合组件内部放置表单是不良实践。
另请参见: - 何时使用、标签文件、组合组件和/或自定义组件?

这是一个更好的解决方案和一个详细而出色的答案。谢谢你提供的链接。我对JSF还很陌生,在还不知道自己在做什么的情况下过于自信地使用了组合组件 :) - Steve Waters

1

我通过手动从后端Bean中获取组件的"type"属性来解决了这个问题,代码如下:

String typeString = (String) component.getAttributes().get("type");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接