Difference between <%= foo %> and ${ foo }

北战南征 提交于 2019-12-12 16:26:08

问题


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 %>

and

${ foo }

回答1:


This, using an old fashioned output scriptlet which is discouraged since a decade,

<%= foo %>

does basically the same as the following in a regular scriptlet:

<% out.println(foo); %>

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);

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.


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);
%>

which is in turn equivalent to:

<% 
    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);
%>

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.



来源:https://stackoverflow.com/questions/19116289/difference-between-foo-and-foo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!