5

我在 Linux 上运行 Tomcat 6.0.18。

我有一个使用这样的 bean 的 JSP:

<jsp:useBean id="helper"
             type="com.example.SomeType"
             scope="request"/>

helper该页面使用如下表达式语言引用 的属性:

<!-- This works properly, but could fail silently if the bean name is incorrect. -->
<div><p>Here's some stuff: ${helper.stuff}</div>

在一些我错过了 name 的重构过程中helper,我注意到如果 name写入不正确,不会引发错误。helper不在屏幕上,也不在我的日志文件中。输出中没有为表达式语言片段生成任何内容:

<!-- Wrong name! "foo" should be "helper" but no error is observed (other than missing ouput)! -->
<div><p>Here's some stuff: ${foo.stuff}</div>

现在,如果我使用以下 JSP 语法且名称不正确,则会引发错误(显示我的自定义错误页面,并且我在日志文件中看到异常)helper

<!-- Wrong name, but an error is raised. -->
<div><p>Here's some stuff: <jsp:getProperty name="foo" property="stuff"/></div>

在这种情况下,日志会记录以下条目:

SEVERE: requestURI: /some.jsp servletName: jsp statusCode: 500
org.apache.jasper.JasperException: Attempted a bean operation on a null object.

为了完整jsp:getProperty起见,当 bean 名称正确时,语法可以正常工作:

<!-- Works properly, protects me from an incorrect name, but is more verbose than EL. -->
<div><p>Here's some stuff: <jsp:getProperty name="helper" property="stuff"/></div>

为什么我在编写 ${foo.stuff} 时没有看到错误?在这种情况下是否有一些配置选项可以控制错误报告?

4

2 回答 2

5

此行为在表达式语言规范版本 2.1的第 1.6 节中进行了介绍。

评估 expr-a[expr-b]:

如果 value-a 为空:

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

(EL 统一了 . 和 [] 运算符)

于 2009-05-26T19:17:45.377 回答
2

这就是 EL 的工作方式。

${helper} 计算结果为 null,因此 EL 只返回 "" 并且不尝试计算表达式的其余部分。

在某些情况下,这是一个方便的功能:

${myBean.property1.name}

即使property1为null也会起作用,因此我不必仅仅为了防止NPE而写:

<c:if test="${not empty myBean.property1}">${myBean.property1.name}</c:if>
于 2009-05-26T19:10:15.207 回答