Question

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 }
Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top