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 }
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Richard Ev
  • 52,939
  • 59
  • 191
  • 278
  • Please don't confuse JSTL with EL. I fixed the tags. To understand the difference, read http://stackoverflow.com/tags/jstl/info and http://stackoverflow.com/tags/el/info – BalusC Oct 01 '13 at 14:07

1 Answers1

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.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555