简体   繁体   English

表达语言:变量与属性

[英]Expression Language: variables vs. attributes

I think I'm missing something basic regarding Expression Language. 我想我错过了一些关于表达语言的基本知识。

practice.jsp (below) outputs 14 , as expected. practice.jsp (下面)输出14 ,如预期的那样。

<jsp:scriptlet>
    request.setAttribute("a", 5);
    request.setAttribute("b", 9);
</jsp:scriptlet>

${a+b}

practice2.jsp (below) outputs 0 . practice2.jsp (下面)输出0

<jsp:scriptlet>
    Integer a = 5;
    Integer b = 9;
</jsp:scriptlet>

${a+b}

What is going on in practice2.jsp? 在practice2.jsp中发生了什么? Why can't EL seem to evaluate these variables? 为什么EL似乎无法评估这些变量? Is this a scope issue, or am I missing something bigger? 这是一个范围问题,还是我错过了更大的东西?

The expression language construct 表达式语言构造

${a + b}

looks for attributes with keys a and b in the page, request, session, and servlet contexts, returning the first it finds. 在页面,请求,会话和servlet上下文中查找具有键ab属性,返回它找到的第一个。 There is no way for it to read variables declared in scriptlets without explicitly adding them to any of those contexts with the key you would like to access them by. 它没有办法读取在scriptlet中声明的变量,而没有使用您想要访问它们的键将它们显式添加到任何上下文中。

I recommend you abandon scriptlets right away, for reasons expressed in this article and others. 我建议您立即放弃scriptlet,原因在于本文和其他文章中表达的原因。

The JSP 2.2 specification describes how variables are resolved: JSP 2.2规范描述了如何解析变量:

 ${product} 

This expression will look for the attribute named product , searching the page, request, session, and application scopes, and will return its value. 此表达式将查找名为product的属性,搜索页面,请求,会话和应用程序范围,并将返回其值。 If the attribute is not found, null is returned. 如果未找到该属性,则返回null。

These scopes are documented as being: 这些范围记录为:

Scriptlets ( <% %> ) are an archaic mechanism that allows you to inject Java code directly into servlets generated from JSP syntax. Scriptlets<% %> )是一种古老的机制,允许您将Java代码直接注入到JSP语法生成的servlet中。 That is, they allow you to inject business logic into your view. 也就是说,它们允许您将业务逻辑注入到视图中。

Since your code doesn't set the values into any of the above scopes they are not visible to the Expression Language variable resolver . 由于您的代码未将值设置为上述任何范围,因此表达式语言变量解析器无法看到它们。

Scope of variables in scirplet is restricted to the scriplet, scirplet中变量的范围仅限于scriplet,
Try this: 尝试这个:

<jsp:scriptlet>
    Integer a = 5;
    Integer b = 9;
    pageContext.setAttribute("a", a);
    pageContext.setAttribute("b", b);
</jsp:scriptlet>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM