h:selectOneRadio映射到布尔值,将nulls转换为false

时间:2016-03-24 14:15:58

标签: jsf jsf-2 null boolean selectoneradio

我有一个h:selectOneRadio组件,我已经映射到辅助bean中的Boolean(不是布尔值)。加载时,单选按钮没有默认选择选项,单选按钮不是必填字段。

示例代码:

JSF页面摘录:

<h:form>
<h:selectOneRadio value="#{pagecode.test}">
    <f:selectItem itemValue="#{true}" itemLabel="Yes"/>
    <f:selectItem itemValue="#{false}" itemLabel="No"/>
</h:selectOneRadio>
<h:commandButton value="Save" action="#{pagecode.save}"/>
</h:form> 

支持Java页面代码:

package pagecode;

public class JSFBooleanTestView extends PageCodeBase {

    protected Boolean test;

    public Boolean getTest() {
        return test;
    }

    public void setTest(Boolean test) {
        this.test = test;
    } 

    public String save() {
        return "JSFBooleanTestView";
    }
}

faces-config.xml摘录:

<managed-bean>
    <managed-bean-name>pagecode</managed-bean-name>
    <managed-bean-class>pagecode.JSFBooleanTestView</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

由于test未默认为某个值,因此单选按钮开始未选中。由于不需要该字段,我的期望是在没有选中单选按钮的情况下按下“保存”按钮会导致测试为空。相反,测试被指定为false。

我尝试过的不同选项没有效果:

  1. 设置h:selectOneRadio required="false"

  2. 添加到web.xml:

    <context-param>
         <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
         <param-value>true</param-value>
     </context-param>
    
  3. 添加到web.xml:

     <context-param>
         <param-name>org.apache.el.parser.COERCE_TO_ZERO</param-name>
         <param-value>false</param-value>
     </context-param>
    
  4. immediate="true"添加到h:commandButton的工作做了什么。

    我的问题:

    1. 是什么让h:selectOneRadio正常地将空值转换为false?这是预期的行为吗?

    2. 为什么immediate="true"使h:commandButton不将空值转换为false? immediate="true"在这种导致差异的特殊情况下做什么不同?我理解immediate="true"将跳过JSF生命周期中的某些阶段,但我不明白这些阶段是什么导致从null转换为false。

    3. 编辑:

      我刚刚意识到我已将immediate="true"添加到h:commandButton而不是 h:selectOneRadio。我的问题已相应编辑。

      使用Apache MyFaces 2.0在IBM WebSphere Portal 8.0上的portlet应用程序中使用它。

1 个答案:

答案 0 :(得分:5)

原始包装器的行为,如BooleanIntegerDoubleCharacter等获得原始​​的默认值false,{ {1}},00.0等已分配而非\u0000特定于Apache EL,用于ao Tomcat,JBoss AS和WebSphere服务器。它仅影响基于EL 2.1和EL 2.2的版本。自EL 3.0以来,这种不当行为得到了纠正(在我自己的issue report之后)。

使用null确实是解决方案,但您应将其设置为VM参数(系统属性),而不是上下文参数。对于此特定问题,org.apache.el.parser.COERCE_TO_ZERO不相关,但您最应保留这一点,以避免使用空字符串而不是javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL设置String类型值。

所有这些以及一些历史记录都在博客文章The empty String madness中详细说明。

另见: