转换器在jsf无法正常工作

时间:2017-01-04 04:11:09

标签: jsf jsf-2 converter

<p:selectOneMenu id="tag1" value="#{attachmentManagement.tag1}" converter="#{stringFilterConverter}">
    <f:selectItems value="#{attachmentManagement.tag1List}" var="tag1" itemLabel="#{not empty tag1.value ? tag1.value : '无'}"/>
</p:selectOneMenu>

<p:commandButton value="button" actionListener="#{attachmentManagement.someFuction()}"/>

当我点击按钮时,抛出了这个异常:

javax.faces.component.UpdateModelException: java.lang.IllegalArgumentException: Cannot convert com.bolan.fzsystem.appserver.view.model.StringFilter@17dbb2e of type class java.lang.String to class com.bolan.fzsystem.appserver.view.model.StringFilter
....
Caused by: java.lang.IllegalArgumentException: Cannot convert com.bolan.fzsystem.appserver.view.model.StringFilter@17dbb2e of type class java.lang.String to class com.bolan.fzsystem.appserver.view.model.StringFilter
....

根本没有调用stringFilterConverter和someFunction。 由于我设置了转换器,为什么jsf不使用它并使用toString()来更新值。

我的转换器实现是一个CDI bean。我找到了解决方案。我将转换器的范围从默认更改为应用程序范围。现在转换器工作。但为什么呢?

这是我的转换器实现:

@Named
@ApplicationScoped //change scope from default to this
public class StringFilterConverter implements Converter, Serializable {
   private static final long serialVersionUID = -6691961589607931061L;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || value.isEmpty()) {
            return ValueFilter.UNDEFINE;
        }
        return JSON.parseObject(value, new TypeReference<String>() {});
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        ValueFilter<String> filter = (ValueFilter<String>) value;
        return JSON.toJSONString(filter);
    }
}

1 个答案:

答案 0 :(得分:0)

在您的代码段中,您将转换器定义为converter="#{stringFilterConverter}"但是我认为您不应该使用EL表达式语法包装转换器的名称,因此转换器的正确用法应该是:

<p:selectOneMenu id="tag1" value="#{attachmentManagement.tag1} converter="stringFilterConverter"/> 

(当然我假设你的转换器实现类有注释@FacesConverter("stringFilterConverter")