java - 使用 setPropertyActionListener 设置 ENUM

标签 java jsf primefaces

我正在尝试使用 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/

相关文章:

java - 使用 Selenium Webdriver 时如何打开通常的 chrome 或 Firefox 窗口?

java - 在java中获取谷歌搜索结果而不被标记

javascript - 是否可以使用 PrimeFaces RemoteCommand 下载文件?

java - 嵌套接口(interface)的 setter

java - 从数据库搜索时 Android Activity 卡住

javascript - 解析错误/page.xhtml : Error Traced[line: 42] Open quote is expected for attribute "{1}" associated with an element type "id"

jsf-2 - 在 JSF 2.0 中设置 OK(提交)按钮

jsf - "Unable to save dynamic action with clientId ' j_idX' 的警告因为找不到 UIComponent"发生,使用 CombinedResourceHandler

validation - 验证 ui :repeat 中项目的顺序

jsf - 如何在地址栏中显示欢迎文件的完整页面 URL