Using Expressions

A JSP expression element is used to insert the result of a scripting code expression into the response. It’s the Java scripting equivalent to an EL expression directly in template text. An expression starts with <%= and ends with %>. Note that the only syntax difference compared to a scriptlet is the equal sign (=) in the start identifier. Examples are:

<%= userInfo.getUserName(  ) %>
<%= 1 + 1 %>
<%= new java.util.Date(  ) %>

The result of the expression is written to the response body, converted to a String if needed. One thing is important to note: as opposed to statements in a scriptlet, the code in an expression must not end with a semicolon. This is because the JSP container combines the expression code with code for writing the result to the response body. If the expression ends with a semicolon, the combined code will not be syntactically correct.

As with EL expressions, a Java expression can also be used to assign a dynamic value to an action element attribute, but with a few restrictions as described later in this chapter.

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.