3

I think I'm missing something basic regarding Expression Language.

practice.jsp (below) outputs 14, as expected.

<jsp:scriptlet>
    request.setAttribute("a", 5);
    request.setAttribute("b", 9);
</jsp:scriptlet>

${a+b}

practice2.jsp (below) outputs 0.

<jsp:scriptlet>
    Integer a = 5;
    Integer b = 9;
</jsp:scriptlet>

${a+b}

What is going on in practice2.jsp? Why can't EL seem to evaluate these variables? Is this a scope issue, or am I missing something bigger?

Brandon Buck
  • 7,177
  • 2
  • 30
  • 51
Jeff Levine
  • 2,083
  • 9
  • 30
  • 38

3 Answers3

3

The expression language construct

${a + b}

looks for attributes with keys a and b in the page, request, session, and servlet contexts, returning the first it finds. There is no way for it to read variables declared in scriptlets without explicitly adding them to any of those contexts with the key you would like to access them by.

I recommend you abandon scriptlets right away, for reasons expressed in this article and others.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
3

The JSP 2.2 specification describes how variables are resolved:

${product}

This expression will look for the attribute named product, searching the page, request, session, and application scopes, and will return its value. If the attribute is not found, null is returned.

These scopes are documented as being:

  • pageScope - a Map that maps page-scoped attribute names to their values
  • requestScope - a Map that maps request-scoped attribute names to their values
  • sessionScope - a Map that maps session-scoped attribute names to their values
  • applicationScope - a Map that maps application-scoped attribute names to their values

Scriptlets (<% %>) are an archaic mechanism that allows you to inject Java code directly into servlets generated from JSP syntax. That is, they allow you to inject business logic into your view.

Since your code doesn't set the values into any of the above scopes they are not visible to the Expression Language variable resolver.

McDowell
  • 107,573
  • 31
  • 204
  • 267
2

Scope of variables in scirplet is restricted to the scriplet,
Try this:

<jsp:scriptlet>
    Integer a = 5;
    Integer b = 9;
    pageContext.setAttribute("a", a);
    pageContext.setAttribute("b", b);
</jsp:scriptlet>
Frederic Close
  • 9,389
  • 6
  • 56
  • 67
  • That doesn't really answer the question but just applies example 1 to example 2. I think your sample would be more clear if you set the result of adding `a` and `b` as an attribute and then accessed it via `${ valueName }` instead. – Brandon Buck Nov 17 '13 at 19:42