<%= foo%>之间的差异和$ {foo} [英] Difference between <%= foo %> and ${ foo }
问题描述
第一次使用JSP进行编码,我需要将变量的值呈现为HTML.看来有多种方法可以做到这一点;两者之间有什么区别(假设我有一个名为foo
的变量)?
Coding in JSP for the first time, I need to render a variable's value to HTML. It looks like there are various ways to do this; what is the difference between these (given that I have a variable named foo
)?
<%= foo %>
和
${ foo }
推荐答案
This, using an old fashioned output scriptlet which is discouraged since a decade,
<%= foo %>
与常规 scriptlet 中的以下内容基本相同:
does basically the same as the following in a regular scriptlet:
<% out.println(foo); %>
与普通的Java servlet类中的以下内容基本相同(您可能已经知道,JSP最终会被编译并转换为servlet类):
which in turn does basically the same as the following in a normal Java servlet class (you probably already know, JSPs ultimately get compiled and converted to a servlet class):
response.getWriter().println(foo);
其中,foo
因此被声明为本地/实例变量.因此,它将本地/实例变量foo
精确地在声明的位置打印到HTTP响应.
where foo
is thus declared as a local/instance variable. It thus prints the local/instance variable foo
to the HTTP response at exactly the declared place.
使用表达式语言(EL),这是自2003年JSP 2.0以来推荐的方法,
This, using expression language (EL), which is the recommended approach since JSP 2.0 in 2003,
${ foo }
does basically the same as the following in a regular scriptlet, with PageContext#findAttribute()
:
<%
Object foo = pageContext.findAttribute("foo");
if (foo != null) out.println(foo);
%>
依次相当于:
<%
Object foo = pageContext.getAttribute("foo");
if (foo == null) foo = request.getAttribute("foo");
if (foo == null) foo = session.getAttribute("foo");
if (foo == null) foo = application.getAttribute("foo");
if (foo != null) out.println(foo);
%>
因此,它将页面/请求/会话/应用程序范围内的属性的第一个非空出现打印到确切声明位置处的响应.如果没有,则什么也不打印.请注意,与 scriptlets 所做的相反,它在null
时不会显示文字字符串"null".
It thus prints the first non-null occurrence of the attribute in the page/request/session/application scope to the response at exactly the declared place. If there is none, then print nothing. Please note that it thus doesn't print a literal string of "null" when it's null
, on the contrary to what scriptlets do.
这篇关于<%= foo%>之间的差异和$ {foo}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!