我有一个JSF支持bean设计问题。现在,我的支持bean持有UI显示信息和业务模态数据。人们建议模型和视图应该分开。那么创建不同的bean持有UI显示数据并有支持bean的参考是不是很好?
答案 0 :(得分:8)
所以最好创建不同的bean持有UI显示数据并有支持参考吗?
是的,否则你继续将数据从模型映射到自己查看,同时你也可以让JSF / EL这样做。顺便说一句,它不一定需要是JSF @ManagedBean
。
E.g。这很糟糕:
@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.
}
与
<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>
这是更好的
@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.
}
与
<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>
另请参阅this JSF 2.0 tutorial提供的示例。