JSTL Expression Tags

printer-friendly version of this section  Print  e-mail this section  E-Mail  add a public, group or private note  Add Note  add a bookmark about this section  Add Bookmark    

JSTL: JSP Standard Tag Library Kick Start
By Jeff Heaton

Table of Contents
Chapter 4.  Using the Expression Language


In JSTL, an expression is always wrapped between the characters ${ and }. For example, the expression for displaying the variable a with 10 added would be ${a+10}. This can easily be incorporated into many of the JSTL tags. The following code would use a <c:out> tag to display the expression a+10:

<c:out value="${a+10}"/> 

Eventually, JSP 2.0 will allow EL expressions to be inserted right into HTML code. For example, the following line in a JSP file would display the expression a+10:

<p>The value of a+10 is ${a+10}</p> 

While the expression language is a powerful feature of JSP 2.0, one of the design requirements for JSTL was compatibility with JSP 1.2. To accommodate JSP 1.2's lack of expression support, Sun added the <c:out> tag to provide a means of displaying a JSTL expression.

The <c:out> tag is not the only tag that JSTL provides that can work with expressions. In addition to the <c:out> tag, JSTL includes several tags that are designed to deal directly with expressions. In the following sections, we explain how to use each of these tags.

Using the <c:out> Tag

The <c:out> tag is used to display a JSTL expression and set the value of a JSTL scoped variable. There are two forms of the <c:out> tag:

// Syntax 1: Without a body <c:out value="value" [escapeXml="{true|false}"] [default="defaultValue"] /> // Syntax 2: With a body <c:out value="value" [escapeXml="{true|false}"]> default value </c:out> 

If you want to display a small amount of text, you should use the bodyless version of the <c:out> tag. This will cause your code to appear more concise because your text will be included in the tag itself. The other version of the <c:out> tag includes a body in order to allow a larger area of text to be displayed. This area can include multiple blank lines, text, and expressions.

Often, the <c:out> tag is used only to display the result of a simple expression. Listing 4.1 shows a simple use of the <c:out> tag.

Listing 4.1 Using the <c:out> Tag (out.jsp)
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html>   <head>     <title>Out Examples</title>   </head>   <body>   <h3>Out Example</h3>   10 * 3 =   <c:out value="${10*3}" />   <br />   </body> </html> 

In Listing 4.1 you can see that the JSP is using the <c:out> tag to display the expression ${10*3). The expression ${10*3) evaluates to 10 times 3, or 30. The expression is well defined and should always have a value. The <c:out> tag will display whatever the value attribute specifies.

Expressions will not always have values. An expression may default to null if there is insufficient information to calculate the expression. Consider the expression ${a}. This expression will display whatever is stored in the a variable. If the a variable has never been defined, then the ${a} expression is considered a null expression. The <c:out> tag lets you specify a default value that will be displayed when the expression that you specified is null. Listing 4.2 shows the <c:out> tag used with a default value.

Listing 4.2 Using the <c:out> Tag with Defaults (outdefault.jsp)
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html>   <head>     <title>Out Default Examples</title>   </head>   <body>testit =   <c:out value="${testit}" default="Default Value" />   </body> </html> 

As you can see, the code in Listing 4.2 attempts to display the value of the variable testit, which has not been defined and has a null value. However, the <c:out> tag specifies a default value. The <c:out> tag in Listing 4.2 will display the text Default Value. Without the default attribute, the code would have simply displayed a blank in place of the null value.

Working with null values in JSTL does not generally throw null exceptions as it does in regular Java. When a null value is accessed or compared, JSTL simply inserts an empty string in place of the null value. This prevents JSTL from throwing a NullPointerException as regular Java would.

As we saw earlier in this section, there are two forms of the <c:out> tag. The first form, which we have already examined, is a single tag that has no body. It is also possible to give a <c:out> tag a body. This body defines what will be output, just like the value attribute defined in the bodyless <c:out> tag.

By default, the <c:out> tag will automatically escape any special characters encountered. This can be good because it allows you to display special HTML reserved characters, such as greater than (>) and less than (<). When the <c:out> tag is presented with a less-than symbol, it will automatically replace the symbol with the HTML code &lt;, which allows HTML to display the less-than symbol. Without this code, HTML would assume that your less-than symbol was the beginning of an HTML tag. Table 4.1 summarizes these special characters.

Table 4.1. Special Characters Encoded by <c:out>

Special Character

Encoded Form

<

&lt;

>

&gt;

&

&amp;

'

&#039;

"

&#034;

The automatic encoding of special characters by the <c:out> tag can also present a problem. You may want to store HTML tags, along with regular text, inside scoped variables. For example, consider the chat program discussed in Chapter 3, "Understanding Basic Tag Logic." Each time the user enters some text, that text is added to an application variable. The following code is responsible for this task:

<c:set var="chat" value="${chat}<b>${param.uid}:</b>${param.text}<br />"  scope="application" /> 

As you can see, this code adds to the already defined chat application variable. In addition to the text that the user has typed, the user's name should be added to the chat tag. The username is bolded before being added to the application variable.

When it comes time to display the chat application variable, it must be displayed without the special characters being encoded. If JSTL were to encode these special characters, the user would literally see <b>username</b> rather than just seeing username in bold characters. Listing 4.3 shows how this encoding works.

Listing 4.3 Using <c:out> with/without Tag Escaping (outescape.jsp)
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html>   <head>     <title>Out with Tag Escaping Examples</title>   </head>   <body>     <c:set var="test" scope="page">       <table border="0">         <tr>           <td bgcolor="red">&#160;</td>           <td bgcolor="green">&#160;</td>         </tr>         <tr>           <td bgcolor="blue">&#160;</td>           <td bgcolor="yellow">&#160;</td>         </tr>       </table>     </c:set>     <h3>Out With Encode=true</h3>     <c:out value="${test}" escapeXml="true" />     <br />     <h3>Out With Encode=false</h3>     <c:out value="${test}" escapeXml="false" />     <br />   </body> </html> 

As you can see in Listing 4.3, the page-scoped variable test is assigned some HTML that will display a multicolored table. The program then displays this variable twice.

The first time the variable is displayed with the escapeXml attribute set to true, which is the default. This is done using the following <c:out> tag:

<c:out value="${test}" escapeXml="true" /> 

Of course, because true is the default, the following line of code would do exactly the same thing:

<c:out value="${test}" /> 

In this case, the colored HTML table will not be displayed; rather, the HTML that makes up the multicolored table will be displayed. Then, the program displays the multicolored table with the escapeXml attribute set to false, which displays the multicolored HTML table correctly. This is accomplished with the following <c:out> tag:

<c:out value="${test}" escapeXml="false" /> 

It is important to properly set this flag so that the program displays your variables correctly. Figure 4.1 shows the output from this program.

Figure 4.1. HTML escaping and the <c:out> tag.

graphics/04fig01.jpg

Using the <c:set> Tag

The <c:set> tag is used to set the value of a JSTL scoped variable. There are four forms of the <c:set> tag:

// Syntax 1: Set using value attribute <c:set value="value" var="varName" [scope="{page|request|session|application}"]/> // Syntax 2: Set the value of a scoped variable using body content <c:set var="varName" [scope="{page|request|session|application}"]> body content </c:set> // Syntax 3: Set the value of a target object using value attribute <c:set value="value" target="target" property="propertyName"/> // Syntax 4: Set the value of a target object using body text <c:set target="target" property="propertyName"> body content </c:set> 

Just as with the <c:out> tag, the <c:set> tag lets you specify a value with the value attribute or use a tag body to specify the value. The bodyless version of <c:set> is generally used when only a small amount of text must be assigned to the variable. The body version of the <c:set> tag can be helpful when a large amount of text should be assigned to the variable, specified by the var attribute of the <c:set> tag. Listing 4.4 shows how to use the <c:set> tag.

Listing 4.4 Using the <c:set> Tag (set.jsp)
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html>   <head>     <title>Set Examples</title>   </head>   <body>   <h3>Set With No Body</h3>   <c:set var="str" value="Hello World" />   str =   <c:out value="${str}" />   <br />   <h3>Set With Body</h3>   <c:set var="str">Hello Again, World</c:set>   str =   <c:out value="${str}" />   <br />   </body> </html> 

Listing 4.4 shows using the <c:set> tag both with and without a body. When used with a body, the <c:set> tag simply specifies both var, which specifies the variable to be set, and value, which specifies the value being set:

<c:out var="str" value="Hello world" /> 

When used with a body, this line becomes:

<c:set var="str">Hello World</c:set> 

The <c:set> tag also allows you to specify scope. We discussed scope in Chapter 2, "Programming the JSP Standard Tag Library."

It is also possible to set a property of an object using the <c:set> tag. Syntax 3 and 4 in our earlier example use this method. The following line of code shows how you would set the text property of an object named obj:

<c:out target="obj" property="text" value="Hello world" /> 

Scope is specified by using the scope attribute of the <c:set> tag. For example, the following set tag would be used to assign session scope:

<c:set var="test" value="Session Level Value" scope="session" /> 

Though not generally advised, it is possible to use the same variable name in two or more scopes. You could assign a different value to a given variable in the page, request, session, and application scopes. Listing 4.5 shows how this is done.

Listing 4.5 Using the <c:set> Tag with Scope (setscope.jsp)
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html>   <head>     <title>Set in Scope Examples</title>   </head>   <body>     <c:set var="test" value="Page Level Value" scope="page" />     <c:set var="test" value="Request Level Value"     scope="request" />     <c:set var="test" value="Session Level Value"     scope="session" />     <c:set var="test" value="Application Level Value"     scope="application" />     <table border="1"> <tr>         <td>           <b>Default Level</b>         </td>         <td>           <c:out value="${test}" />         </td>       </tr>       <tr>         <td>           <b>Page Level</b>         </td>         <td>           <c:out value="${pageScope.test}" />         </td>       </tr>       <tr>         <td>           <b>Request Level</b>         </td>         <td>           <c:out value="${requestScope.test}" />         </td>       </tr>       <tr>         <td>           <b>Session Level</b>         </td>         <td>           <c:out value="${sessionScope.test}" />         </td>       </tr>       <tr>         <td>           <b>Application Level</b>         </td>         <td>           <c:out value="${applicationScope.test}" />         </td>       </tr>     </table>   </body> </html> 

The code in Listing 4.5 assigns a different value to the variable test in each of the scopes. When it's time to display test, you must tell JSTL which of the four scopes you would like displayed. You do this by prefixing the variable name with the scope name, followed by a period. For example, to specify that you would like to display the variable from the application scope, you would use the following line of code:

<c:out value="${applicationScope.test}" /> 

By specifying the scope, you are assured of getting the correct value. If you don't specify the scope, JSTL will begin looking for the variable in page scope. If it doesn't find your variable in page scope, JSTL then checks request, session, and finally application scope. The output from this program is shown in Figure 4.2.

Figure 4.2. Variable scopes.

graphics/04fig02.jpg

Using the <c:remove> Tag

The <c:remove> tag is a scoped variable. There is only one form of the <c:remove> tag:

<c:remove var="varName" [scope="{page|request|session|application}"]/> 

Removing a variable makes the memory space being used by that variable available for other variables that might be stored by your Web application. In actual programming practice, the <c:remove> tag is not used all that often. Page- and request-scoped variables are generally used for temporary variables, and they do not have to be removed manually they will be automatically removed when the page exits. It is considered good programming practice to keep your session-scoped variables to a minimum, so temporary variables are rarely assigned to session scope. In addition, using temporary values in the application scope can cause threading problems. This is because many threads will be accessing your variable simultaneously. In any case, session-scoped variables are automatically removed when the session ends.

The <c:remove> tag can be useful when a value is assigned to application-level scope to be communicated to other sessions. In this case, the variable should be removed once it is no longer needed because it will not be removed automatically until either the Web server is shut down or the Web application is restarted.

Another somewhat common use of the <c:remove> tag is with session variables. Sometimes, it is necessary to take the user through a multiform input series. In such a situation, the user is presented with a series of forms that collects more and more information from the user. This data is not yet ready to be saved; it is not complete until the user reaches the final page. The data can be stored in a session variable that will be removed once the user either abandons the process or saves the form. Although this is a common technique, you should ensure that you do not store too much data in the user session due to the overhead incurred.

A technique for avoiding using session variables is to put intermediate data in hidden fields. This data will then be posted to subsequent forms and the program will still have access to it. This approach also protects the data from session expirations.

Listing 4.6 shows an application that uses the <c:remove> tag.

Listing 4.6 Using the <c:remove> Tag (remove.jsp)
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html>   <head>     <title>Remove Examples</title>   </head>   <body>   <h3>Remove Example</h3>   <c:set var="test" value="Hello World" scope="page" />   The value in the variable test before remove is   <c:out value="${test}" />   <br />   <c:remove var="test" scope="page" />   The value in the variable test after remove is   <c:out value="${test}" />   <br />   </body> </html> 

The program in Listing 4.6 assigns the value Hello World to the variable test. The value stored in test is displayed to the browser. Then, the JSP page uses the <c:remove> tag to remove test. This is done with the following line:

<c:remove var="test" scope="page" /> 

This code will remove test. When test is redisplayed a few lines below the <c:remove> tag, a blank is displayed. This is because the removed test variable now has a null value. JSTL always displays nulls as blanks. However, if you run setscope.jsp first, the result will be Session Level Value.


    printer-friendly version of this section  Print  e-mail this section  E-Mail  add a public, group or private note  Add Note  add a bookmark about this section  Add Bookmark    
    Top

    [0672324504/ch04lev1sec1]

     
     


    JSTL. JSP Standard Tag Library Kick Start
    JSTL: JSP Standard Tag Library Kick Start
    ISBN: 0672324504
    EAN: 2147483647
    Year: 2001
    Pages: 93
    Authors: Jeff Heaton

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net