Displaying Values

Besides using scriptlets for conditional output, one more way to employ scripting elements is by using a JSP expression element to insert values into the response. A JSP expression element can be used instead of the <jsp:getProperty> action in some places, but it is also useful to insert the value of any Java expression that can be treated as a String.

An expression starts with <%= and ends with %>. Note that the only syntax difference compared to a scriptlet is the equals sign (=) in the start identifier. An example is:

<%= userInfo.getUserName( ) %>

The result of the expression is written to the response body. 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.

In the final example of Chapter 5, we used <jsp:getProperty> actions to fill out the form fields with UserInfoBean values. To recap, it looked like this:

<tr>
  <td>Name:</td>
  <td><input type="text" name="userName" 
    value="<jsp:getProperty
             name="userInfo"
             property="userNameFormatted"
           />">
  </td>
</tr>

In this case, the <jsp:getProperty> syntax is distracting, since it’s used as the value of an HTML element. You can use expressions to make the user input form page easier to read. The following example shows the same part of the ...

Get Java Server Pages 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.