【问题标题】:h:selectOneRadio is passing null character instead of null valueh:selectOneRadio 正在传递空字符而不是空值
【发布时间】:2015-12-29 19:30:03
【问题描述】:

在我的 JSF 页面代码中,我有类似以下内容:

<h:selectOneRadio value="#{pagecode.attending}" required="true" id="attendingRadio" binding="#{attendingRadio}">
    <f:selectItem itemValue="Y" itemLabel="Yes"/>
    <f:selectItem itemValue="N" itemLabel="No"/>
    <f:ajax event="click" render="attendingDetails" execute="attendingRadio"/>
</h:selectOneRadio>
<h:panelGroup id="attendingDetails">
    <h:panelGroup rendered="#{pagecode.showForm(attendingRadio.value)}">
        ...
    </h:panelGroup>
</h:panelGroup>

在我的页面代码支持 bean 中,我有如下内容:

public class Pagecode {
    protected Character attending;

    public Character getAttending() {
        return attending;
    }

    public void setAttending(Character attending) {    
        this.attending=attending;
    }

    public boolean showForm(Character c) {
        if (c==null) {
            return false;
        }
        (other stuff)...
    }

}

我期望的行为是:

  1. 页面加载。单选按钮未定义为初始值,因此既未选择 Yes 也未选择 No。但是,由于 required="true",如果用户将其留空(确实如此),用户将收到验证错误。
  2. 第一次加载页面时,调用#{pagecode.showForm(attendingRadio.value)},我希望传递一个空对象,而showForm 将返回false。

在进行了一些故障排除后,我确定实际发生的情况是,不是传递空对象,即等效为 showForm(null),而是得到等效于 showForm(new Character('\u0000'));而是将 Unicode 字符传递给 null。

当我的 h:selectOneRadio 没有选择值时,有没有办法让 JSF 传递 Java 空对象而不是空字符?我在 WebSphere Portal 8.0 上使用 Apache MyFaces JSF 2.0。

附带说明一下,我确实尝试将以下内容添加到我的 web.xml 中,但不幸的是它没有帮助:

<context-param>
   <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
   <param-value>true</param-value>
</context-param>

【问题讨论】:

    标签: jsf jsf-2 selectoneradio null-check null-character


    【解决方案1】:

    Character/char 对于您要表示的值来说只是一个错误的数据类型。

    请改用enum

    public enum Choice {
        Y, N;
    }
    

    private Choice attending;
    

    或者,可能更好,Boolean

    private Boolean attending;
    

    <f:selectItem itemValue="true" itemLabel="Yes" />
    <f:selectItem itemValue="false" itemLabel="No" />
    

    【讨论】:

    • 虽然我同意,但不幸的是,我不能在这个项目中轻易改变——我提供的代码示例是一个简化。参加的角色实际上不在主要的 Pagecode 类中,而是在作为子类属性的另一个对象中,不幸的是,该类是其他几个项目使用的共享库的一部分。我想改变它,但目前我不能。即使只是出于好奇,有没有办法让 h:selectOneRadio 发送 null 而不是 null 字符?似乎是一个奇怪的实现。
    • 责备 EL,而不是 JSF。您可以尝试禁用 COERCE_TO_ZERO。相关:balusc.omnifaces.org/2015/10/the-empty-string-madness.html
    • 我刚刚使用 COERCE_TO_ZERO 参数对此进行了测试,并且可以验证它是否已修复。该行为与该问题有关。谢谢!
    猜你喜欢
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    相关资源
    最近更新 更多