JSF MVC design question

[亡魂溺海] 提交于 2020-01-22 09:58:10

问题


I have a JSF backing bean design question. right now, my backing bean is holding UI display information and also business modal data. people suggest that model and view should be separated. so is it good idea to create different bean holding UI display data and have backing bean have reference to it?


回答1:


so is it good idea to create different bean the holding UI display data and have backing have reference to it?

Yes, otherwise you keep mapping the data from model to view yourself while you can also just let JSF/EL do that. It does by the way not necessarily need to be a JSF @ManagedBean.

E.g. this is poor:

@ManagedBean
@RequestScoped
public class ProductEditor {

    private String productName;
    private String productDescription;
    private BigDecimal productPrice;

    public String add() {
        Product product = new Product();
        product.setName(productName);
        product.setDescription(productDescription);
        product.setPrice(productPrice);
        productService.save(product);
        return "view";
    }

    // In total 6 getters and setters.
}

with

<h:form>
    <h:inputText value="#{productEditor.productName}" />
    <h:inputTextarea value="#{productEditor.productDescription}" />
    <h:inputText value="#{productEditor.productPrice}">
        <f:convertNumber type="currency" currencySymbol="$" />
    </h:inputText>
    <h:commandButton value="Add" action="#{productEditor.add}" />
</h:form>

This is better

@ManagedBean
@RequestScoped
public class ProductEditor {

    private Product product;

    @PostConstruct
    public void init() {
        product = new Product(); // You could also preload from DB based on some ID as request parameter.
    }

    public String add() {
        productService.save(product);
        return "view";
    }

    // Only 1 getter.
}

with

<h:form>
    <h:inputText value="#{productEditor.product.name}" />
    <h:inputTextarea value="#{productEditor.product.description}" />
    <h:inputText value="#{productEditor.product.price}">
        <f:convertNumber type="currency" currencySymbol="$" />
    </h:inputText>
    <h:commandButton value="Add" action="#{productEditor.add}" />
</h:form>

See also the examples as presented by this JSF 2.0 tutorial.



来源:https://stackoverflow.com/questions/5706128/jsf-mvc-design-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!