Difference between <%= foo %> and ${ foo }
Asked Answered
D

1

3

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 }
Dogmatize answered 1/10, 2013 at 12:33 Comment(1)
Please don't confuse JSTL with EL. I fixed the tags. To understand the difference, read stackoverflow.com/tags/jstl/info and stackoverflow.com/tags/el/infoSinatra
S
5

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.

Sinatra answered 1/10, 2013 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.