【问题标题】:JSP Expression Language Error Behavior?JSP 表达式语言错误行为?
【发布时间】:2009-05-26 18:53:27
【问题描述】:

我在 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>

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

<!-- 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 的名称不正确,则会引发错误 (显示我的自定义错误页面,并且我在日志文件中看到异常): p>

<!-- 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} 时没有看到错误?在这种情况下是否有一些配置选项可以控制错误报告?

【问题讨论】:

  • 只是为了肯定别人所说的,这是EL的一个有目的的功能。

标签: jsp tomcat el


【解决方案1】:

Expression Language Specification Version 2.1 的第 1.6 节介绍了此行为。

计算 expr-a[expr-b]:

如果 value-a 为空:

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

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

【讨论】:

  • 感谢@McDowell 的回答。澄清一下:“ValueExpression.getValue(context)”== 使用 EL 读取一个值(这是我在这个问题中所做的),以及“尝试为左值取消引用 null”== 使用 EL写一个值。规范的第 1.4 节讨论了观察到的行为的基本原理。哦,“return null”在这种情况下意味着“产生空字符串”——规范第 1.18.2 节
【解决方案2】:

这正是 EL 的工作方式。

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

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

${myBean.property1.name}

即使 property1 为空也可以工作,因此我不必仅仅为了防止 NPE 而写:

<c:if test="${not empty myBean.property1}">${myBean.property1.name}</c:if>

【讨论】:

    猜你喜欢
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多