首页 > 解决方案 > 无法在 JSF 中自动转换枚举

问题描述

根据这个答案:https://stackoverflow.com/a/8229982/988145,JSF应该自动转换枚举。出于某种原因,它没有。我收到以下错误:

“‘空转换器’的频率转换错误设置值‘DAY_OF_WEEK’的类型。”

我的枚举:

public enum FrequencyType implements Serializable
{
    DAY_NUMBER, DAY_OF_WEEK
}

选择标记:

<h:selectOneMenu onchange="toggleFrequencyTypes(this);" 
         value="#{cellContentsBean.pillSheetProfile.frequency}" 
         class="form-control" id="frequencyTypeDd">
    <f:selectItems value="#{cellContentsBean.frequencyTypes}" />
</h:selectOneMenu>

bean中的频率类型getter:

public FrequencyType[] getFrequencyTypes() {
    return FrequencyType.values();
}

二传手:

private FrequencyType frequencyType;

/**
 * @return the frequencyType
 */
public FrequencyType getFrequencyType()
{
    return frequencyType;
}

/**
 * @param frequencyType the frequencyType to set
 */
public void setFrequencyType(FrequencyType frequencyType)
{
    this.frequencyType = frequencyType;
}

正如另一个线程所暗示的那样,我什至在我的面孔配置中添加了一个转换器,但它什么也没做:

<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
              xmlns="http://java.sun.com/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_2.xsd">
    <application>
        <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>

        <converter>
            <converter-for-class>java.lang.Enum</converter-for-class>
            <converter-class>javax.faces.convert.EnumConverter</converter-class>
        </converter>
    </application>
</faces-config>

标签: jsf

解决方案


虽然这可能无法解决您的问题,但我必须注意您的 faces-config.xml 有点损坏:

  1. 您声明的 JSF 命名空间不存在这种方式
  2. 错误的元素嵌套:converter元素不是元素的子application元素。

最好试试这个:

<?xml version='1.0' encoding='UTF-8'?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">
    <application>
        <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
    </application>

    <converter>
        <converter-for-class>java.lang.Enum</converter-for-class>
        <converter-class>javax.faces.convert.EnumConverter</converter-class>
    </converter>
</faces-config>

推荐阅读