我正在尝试使用 setPropertyActionListener 设置枚举属性,但我不知道该怎么做。这是实体:
@Entity
public class Invoice {
public enum InvoiceStatus { ACTIVE, CANCELED }
...
@Enumerated(EnumType.STRING)
private InvoiceStatus status;
...
public InvoiceStatus getStatus() {
return status;
}
public void setStatus(InvoiceStatus status) {
this.status = status;
}
这是命令按钮,它应该使用 setPropertyActionListener 将状态设置为 ACTIVE
...
<h:form id="invoiceCreatedSuccessfully">
<p:dialog header="#{msg['title.success']}" widgetVar="invoiceCreatedSuccessfullyDialog" resizable="false" showEffect="fade" hideEffect="fade">
<h:panelGrid columns="2" rows="3" style="margin-bottom: 10px">
<h:outputText value="#{msg['message.invoiceCreatedSuccessfully']}" />
</h:panelGrid>
<p:commandButton value="#{msg['label.acknowledged']}" actionListener="#{invoiceManager.reload}" action="viewInvoices">
<f:setPropertyActionListener target="#{invoiceManager.invoice.status}" value="ACTIVE" />
</p:commandButton>
</p:dialog>
</h:form>
未报告任何错误,但未设置数据库中的“状态”字段。谁能告诉我为什么?
最佳答案
EL 中的字符串不会直接转换为枚举,您需要在 faces-config 中进行自定义转换,jsf 有一个适合您的枚举转换器,
<converter>
<converter-for-class>java.lang.Enum</converter-for-class>
<converter-class>javax.faces.convert.EnumConverter</converter-class>
</converter>
罢工><罢工>罢工>
现在查看 EnumConverter 的源代码,似乎只有当 targetClass 在转换器中可用时它才有效。
因此您需要扩展它以与您的枚举一起使用,
public class MyEnumConverter extends EnumConverter {
public MyEnumConverter () {
super(MyEnum.class);
}
}
<converter>
<converter-id>MyEnum</converter-id>
<converter-class>com.test.MyEnumConverter</converter-class>
</converter>
添加<f:converter converterId="MyEnum"/>
在您的组件中。
如果您有很多枚举并且为了让事情变得简单,您可以查看omnifaces http://showcase.omnifaces.org/converters/GenericEnumConverter
关于java - 使用 setPropertyActionListener 设置 ENUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15571980/