Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top