1

我有一个实体 OrderLine,其中包含 unitPrice、quantity 和 totalPrice 字段。并计算 totalPrice 值:totalPrice=unitPrice*quantity。

totalPrice 是一个持久字段。

我想在视图中将 totalPrice 显示为输出文本。

第一个替代方案: <h:outputText id="total" value="#{unitPrice*quantity}"/> 使用此替代方案,实体字段 totalPrice 将永远不会更新,但在视图中将显示总价的正确值。

第二种选择:<h:outputText id="total" value="#{orderLine.totalPrice }"/>

使用这种替代方法,将从数据库中获取的值将被显示,但该值将始终为空。

是否可以仅使用 JSF,在显示页面时显示值 #{orderLine.totalPrice },并在同一页面中修改 unitPrice 或数量时设置其更新值 #{unitPrice*quantity}?

感谢

4

2 回答 2

2

如果我是你,我可能会尝试在客户端使用一些带有 jQ​​uery 的 JavaScript 来完成。

但是如果你真的想用纯 Java 和 JSF 来做,你可以做的一件事是totalPrice在其中一个字段unitPrice或更新时更新该字段quantity

public void setUnitPrice(BigDecimal unitPrice) {
    this.unitPrice = unitPrice;
    this.updateTotalPrice();
}
public void setQuantity(BigDecimal quantity) {
    this.quantity = quantity;
    this.updateTotalPrice();
}
private void updateTotalPrice() {
    // update total price accordingly:
    if (unitPrice != null && quantity != null){
        this.totalPrice = this.unitPrice.multiply(this.quantity);
    }
}

这样,您的模型也将始终保持最新。

然后,您只需要onchangeunitPricequantity表单控件的事件上重新渲染使用 ajax 显示它的组件,如下所示:

<h:panelGrid>
    <label>Unit Price</label>
    <h:inputText value="#{myBean.unitPrice}">
        <f:convertNumber type="currency" />
        <f:ajax render="totalPrice" />
    </h:inputText>
    <label>Quantity</label>
    <h:inputText value="#{myBean.quantity}">
        <f:convertNumber type="currency" />
        <f:ajax render="totalPrice" />
    </h:inputText>
    <h:outputText id="totalPrice" value="#{myBean.totalPrice}">
        <f:convertNumber type="currency" />
    </h:outputText>
</h:panelGrid>
于 2012-07-14T17:10:37.953 回答
1

您可能需要使用包装器将逻辑放入包装的 getTotalPrice 方法中,而不是直接使用实体。这样,您就有了更好的逻辑/表示分离,在这种情况下,您将能够向 getTotalPrice 添加舍入逻辑(大多数情况下,IEEE 浮动数学不适合与金钱相关的数学......)

于 2012-07-14T13:32:24.803 回答