0

我创建了一个地址 bean,我想使用它两次——一次用于街道地址,一次用于邮寄地址。我可以按照下面的方法使用 faces config 来实现这一点,但我想知道我是否可以通过注释来做到这一点。

例如将@ManagedBean(name="StreetAddress") 和@ManagedBean(name="MailingAddress") 放在同一个类上?我觉得我在这里遗漏了一些明显的东西,但我不确定是什么。

<managed-bean>
    <managed-bean-name>MailingAddress</managed-bean-name>
    <managed-bean-class>com.leetb.jsf_ex1.model.AddressBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    <map-entries/>
</managed-bean>
<managed-bean>
    <managed-bean-name>StreetAddress</managed-bean-name>
    <managed-bean-class>com.leetb.jsf_ex1.model.AddressBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    <map-entries/>
</managed-bean>

public class AddressBean {

    private String line_one;
    private String line_two;
    private String suburb;
    private String state;
    private String postcode;

/* getters and setters snipped */
}
4

1 回答 1

1

你有一个设计错误。这些看起来更像模型类而不是支持 bean 类。模型类根本不应该是托管 bean。使它们成为支持 bean 类的属性并改为管理它。

例如

@ManagedBean
@ViewScoped
public class AddressBacking {

    private AddressBean mailingAddress;
    private AddressBean streetAddress;

    @PostConstruct
    public void init() {
        // Prepare them here yourself. For example, when it's for a new entry.
        mailingAddress = new AddressBean();
        streetAddress = new AddressBean();
    }

    public void save() {
        // ...
    }

    // ...
}

(顺便说一下,我会重命名AddressBeanAddress

并按如下方式使用

<h:inputText value="#{addressBacking.mailingAddress.line_one}" />
...
<h:inputText value="#{addressBacking.streetAddress.line_one}" />
...
于 2012-06-02T16:37:44.970 回答