使用EL访问对象属性时必须进行空检查

时间:2015-02-16 01:41:19

标签: html jsp null jstl el

在设置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进行这些检查?

1 个答案:

答案 0 :(得分:4)

当您通过EL阅读房产时,您不需要执行该检查。这就是EL的所谓 null-safety 设计特性。

那就是说,这个答案旨在解释为什么会这样。要背诵EL 3.0 specification,关于运算符.的第1.6条(相当于运算符[]):

  

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

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

(强调我的)。

由于您的表达式${data.getAttribute()}是一个值表达式,在data == null为真的情况下使用参数化方法调用语法,null它将作为data.getAttribute()的结果返回评价。一旦这个EL表达式求值的输出是一个字符串,它的值null就会被强制转换为""(空字符串),符合EL 3.0规范的第1.23.2节。

另请注意,JSTL(用于构建HTML的标记集,如<c:choose>与EL不相等<(用于通过{访问和操作应用程序数据的代码段) {1}})。有关更多信息,请参阅our EL wiki page