具有复杂对象的selectOneMenu,是否需要转换器? [英] selectOneMenu with complex objects, is a converter necessary?

查看:101
本文介绍了具有复杂对象的selectOneMenu,是否需要转换器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用任意用户创建的类作为其值的<h:selectOneMenu><p:selectOneMenu>是否需要转换器?我的意思是,下面的代码应该在没有转换器的情况下工作吗?

Is a Converter necessary for a <h:selectOneMenu> or <p:selectOneMenu> with arbitrary user-created classes as its values? I mean, is the following code supposed to work without a converter?

<p:selectOneMenu value="#{bean.language}">
    <f:selectItems value="#{bean.allLanguages}" />
</p:selectOneMenu>

@Named(value = "bean")
@ConversationScoped
public class Bean {

    private Language language; // appropriate getter and setter are present

    public List<SelectItem> getAllLanguages() {
        // populates a list of select items with Strings as item labels and Languages as item values
    }

}

我有一个类似的代码,其中enum作为类型(语言),并且运行良好.但是,当我用普通的Java类替换类型时,会出现转换错误.

I have a similar code with an enum as the type (Language) and it works perfectly. But when I replace the type with a normal java class, I get a conversion error.

推荐答案

在这里您需要一个转换器,因为JSF默认情况下会采用字符串,这就是您编码的方式. JSF不知道如何将伪实体转换为字符串,反之亦然.

You need a converter here, as JSF will assume strings by default, that is the way you coded it. JSF has no idea how to convert your pseudo entities to strings and vice versa.

一些注意事项:

1.您的getAsString方法定义了您的实体/POJO的标识符,而不是JSF(或其他)选择的作为itemLabel的标识符.

1 . Your getAsString method defines your identifier for your entities/POJOs, not what the JSF (or whatever) select gets as itemLabel.

2.您可以使用这篇臭名昭著的文章,深入了解实际实体的数据库:

2 . Your converter can dig into the DB for real entities using this infamous article:

http://balusc.blogspot.de/2011/09/communication-in-jsf-20.html#ConvertingAndValidatingGETRequestParameters

您还可以在该模式"中使用CDI注释.

You can also use CDI annotations with that "pattern".

3.您的value = "bean"是多余的,选择的CDI范围通常是@ViewScoped.但是,必须记住,如果不使用Seam 3或Apache MyFaces CODI,CDI @Named + JSF @ViewScoped不能一起工作.

3 . Your value = "bean"is redundant and the CDI scope of choice is usually @ViewScoped. However, you have to keep in mind that CDI @Named + JSF @ViewScoped isn't working together without using Seam 3 or Apache MyFaces CODI.

这篇关于具有复杂对象的selectOneMenu,是否需要转换器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆