【问题标题】:Necessity of null-checking when accessing object properties with EL使用 EL 访问对象属性时需要进行空值检查
【发布时间】:2015-02-16 01:41:18
【问题描述】:

在设置 HTML 之前,我曾经使用 JSTL 来测试 null 的值。但我最终得到了一个冗长的代码片段:

<c:choose>
    <c:when test="${data == null}">
        <input type ='text'>
        <input type ='text'>
        <input type ='text'>
        <input type ='text'>
        <input type ='text'>
    </c:when>
    <c:otherwise>
        <input type ='text' value= "${data.getAttribute1()}">
        <input type ='text' value= "${data.getAttribute2()}">
        <input type ='text' value= "${data.getAttribute3()}">
        <input type ='text' value= "${data.getAttribute4()}">
        <input type ='text' value= "${data.getAttribute5()}">
    </c:otherwise>
</c:choose>

但是当我不使用 JSTL 时,我仍然得到正确的 HTML 页面而没有任何错误,并且当页面没有调用控制器时,似乎没有任何问题。代码如下:

<input type ='text' value= "${data.getAttribute1()}">
<input type ='text' value= "${data.getAttribute2()}">
<input type ='text' value= "${data.getAttribute3()}">
<input type ='text' value= "${data.getAttribute4()}">
<input type ='text' value= "${data.getAttribute5()}">

我只是浪费代码行来检查null吗?

【问题讨论】:

    标签: html jsp null jstl el


    【解决方案1】:

    当您通过 EL 读取属性时,无需执行该检查。这就是EL的所谓null-safety设计特点。

    也就是说,这个答案旨在解释为什么会这样。背诵EL 3.0 specification,第1.6 条关于运营商.(这反过来相当于运营商[]):

    评估 expr-a[expr-b] 或expr-a[expr-b](参数)

    • 将 expr-a 评估为 value-a
    • 如果 value-a 为空
      • 如果 expr-a[expr-b] 是最后被解析的属性:
        • 如果表达式是值表达式并且调用了 ValueExpression.getValue(context) 来启动此表达式评估,返回 null
        • 否则,抛出 PropertyNotFoundException [试图为左值取消引用 null];
      • 否则,返回 null。

    (强调我的)。

    由于您的表达式${data.getAttribute()} 是一个使用参数化方法调用语法的值表达式,如果data == null 为真,null 将作为data.getAttribute() 评估的结果返回。根据 EL 3.0 规范的第 1.23.2 条,只要此 EL 表达式评估的输出是字符串,其值 null 就会强制转换为 ""(空字符串)。

    另请注意,JSTL(用于构建 HTML 的一组标签,如 &lt;c:choose&gt;不等于 EL(用于通过 ${expression} 访问和操作应用程序数据的代码片段)。更多信息请咨询our EL wiki page

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 2023-01-11
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多