Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

The center of JSTL is the core taglib. This can be split into five areas:

  1. General purpose

  2. Variables support

  3. Conditional

  4. Iterator

  5. URL Related

To use the core library, use the following directive:


<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

					
The prefix attribute specifies the prefix used in the tag name for a particular library. For example, the core library includes a tag named out. When combined with a prefix of c, the full tag would be <c:out>. You are free to use any prefix you like, but you must use different prefixes for each of the four standard tag libraries.

You must also put the corresponding .tld file for each tag library in your /WEB-INF directory and use the taglib element in your web.xml file to include the tag library:


<taglib>
    <taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
    <taglib-location>/WEB-INF/tld/core.tld</taglib-location>
</taglib>

					

General purpose tags.

The general-purpose tags let you display variable values, and enclose a group of tags within a try-catch block.

The <c:out> action provides a capability similar to JSP expressions such as <%= scripting-language-expression %> or ${el-expression}. For example:


You have <c:out value="${sessionScope.user.itemCount}"/> items.

					
By default, <c:out> converts the characters <, >, ', ", & to their corresponding character entity codes (e.g. < is converted to &lt;). If these characters are not converted, the page may not be rendered properly by the browser, and it could also open the door for cross-site scripting attacks. The conversion may be bypassed by specifying false to the escapeXml attribute. The <c:out> action also supports the notion of DEFAULT values for cases where the value of an EL expression is null. In the example below, the value "unknown" will be displayed if the property city is not accessible.

<c:out value="${customer.address.city}" default="unknown"/>

					
The second option is to specify the default value as the content of the <c:out> tag:

<c:out value="${customer.address.street}">
    No address available
</c:out>

					

Syntax:

Without a body:


<c:out value="value" [escapeXml="{true|false}"]
	[default="defaultValue"] />

					
With a body (contains default value):

<c:out value="value" [escapeXml="{true|false}"]>
	default value
</c:out>

					

The <c:catch> action allows page authors to handle errors from any action in a uniform fashion, and allows for error handling for multiple actions at once. <c:catch> provides page authors with granular error handling: Actions that are of central importance to a page should not be encapsulated in a <c:catch>, so their exceptions will propagate to an error page, whereas actions with secondary importance to the page should be wrapped in a <c:catch>, so they never cause the error page mechanism to be invoked. The exception thrown is stored in the scoped variable identified by var, which always has page scope. If no exception occurred, the scoped variable identified by var is removed if it existed. If var is missing, the exception is simply caught and not saved.

Syntax:


<c:catch [var="varName"]>
	nested actions
</c:catch>
					
					

Variables support tags.

The action <c:set> is used to set the value of a JSP scoped attribute as follows:


<c:set var="foo" value="value"/>

					

In the following example, the <c:set> action sets the value of the att1 scoped variable to the output of the acme:foo action. <c:set> – like all JSTL actions that create scoped attributes – creates scoped attributes in 'page' scope by DEFAULT:


<c:set var="att1">
	<acme:foo>mumbojumbo</acme:foo>
</c:set>

<acme:atag att1="${att1}"/>

					
<c:set> may also be used to set the property of a JavaBeans object, or add or set a specific element in a java.util.Map object. For example:
					
<!-- set property in JavaBeans object -->
<c:set target="${cust.address}" property="city" value="${city}"/>

<!-- set/add element in Map object -->
<c:set target="${preferences}" property="color" value="${param.color}"/>

					

Syntax.

Syntax 1: Set the value of a scoped variable using attribute value:

					
<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 a property of a target object (JavaBean object with setter property property, or a java.util.Map object) using attribute value:
					
<c:set value="value" target="target" property="propertyName"/>

					
Syntax 4: Set a property of a target object (JavaBean object with setter property property, or a java.util.Map object) using body content:

<c:set target="target" property="propertyName">
	body content
</c:set>

					

The <c:remove> action removes a scoped variable. If attribute scope is not specified, the scoped variable is removed according to the semantics of PageContext.removeAttribute(varName). If attribute scope is specified, the scoped variable is removed according to the semantics of PageContext.removeAttribute(varName, scope).

Syntax:


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

					

Conditional tags.

A simple conditional execution action evaluates its body content only if the test condition associated with it is true. In the following example, a special greeting is displayed only if this is a user’s first visit to the site:

					
<c:if test="${user.visitCount == 1}">
	This is your first visit. Welcome to the site!
</c:if>
					
					

If the test condition evaluates to true, the JSP container processes the body content (JSP) and then writes it to the current JspWriter.

Syntax:

Syntax 1: Without body content:


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

					
Syntax 2: With body content:

<c:if test="testCondition"
	[var="varName"] [scope="{page|request|session|application}"]>
	body content (JSP)
</c:if>

					

The name of the exported scoped variable var for the resulting value of the test condition. The type of the scoped variable is Boolean.

The <c:choose> tag works like a Java switch statement in that it lets you choose between a number of alternatives. Where the switch statement has case statements, the <c:choose> tag has <c:when> tags. In a switch statement, you can specify a default clause to specify a default action in case none of the cases match. The <c:choose> equivalent of default is <c:otherwise> (optional), but note, it MUST be the LAST action nested within <c:choose>.

Syntax:


<c:choose>
	body content (<when> and <otherwise> subtags)
</c:choose>

					

<c:when test="testCondition">
	body content
</c:when>

					

<c:otherwise>
	conditional block
</c:otherwise>

					

Iterator tags.

The <c:forEach> action repeats its nested body content over the collection of objects specified by the items attribute. For example, the JSP code below creates an HTML table with one column that shows the default display value of each item in the collection:


<table>
	<c:forEach var="customer" items="${customers}">
		<tr><td>${customer}</td></tr>
	</c:forEach>
</table>

					

A large number of collection types are supported by <c:forEach>, including all implementations of java.util.Collection (includes List, LinkedList, ArrayList, Vector, Stack, Set), and java.util.Map (includes HashMap, Hashtable, Properties, Provider, Attributes).

Arrays of objects as well as arrays of primitive types (e.g. int) are also supported. For arrays of primitive types, the current item for the iteration is automatically wrapped with its standard wrapper class (e.g. Integer for int, Float for float, etc.).

If the items attribute is of type java.util.Map, then the current item will be of type java.util.Map.Entry, which has the following two properties: key - the key under which this item is stored in the underlying Map; value - the value that corresponds to this key.

Syntax.

Syntax 1: Iterate over a collection of objects:

					
<c:forEach [var="varName"] items="collection"
	[varStatus="varStatusName"]
	[begin="begin"] [end="end"] [step="step"]>
	
	body content (JSP)
	
</c:forEach>

					
Syntax 2: Iterate a fixed number of times:

<c:forEach [var="varName"]
	[varStatus="varStatusName"]
	begin="begin" end="end" [step="step"]>
	
	body content (JSP)
	
</c:forEach>

					
If specified, begin must be >= 0. If end is specified and it is less than begin, the loop is simply not executed. If specified, step must be >= 1. If items is null, it is treated as an empty collection, i.e., no iteration is performed. If begin is greater than OR EQUAL to the size of items, NO iteration is performed.

Examples:


<c:forEach var="i" start="1" end="10">
   Item <c:out value="${i}/><p>
</c:forEach>

					

<c:forEach var="emp" items="employees">
   Employee: <c:out value="${emp.name}"/>
</c:forEach>

					

<c:forTokens> iterates over tokens, separated by the supplied delimiters. The items attribute specifies the string to tokenize and the delimiters attribute specifies a list of delimiters (similar to the way java.util.StringTokenizer works).

Syntax:


<c:forTokens items="stringOfTokens" delims="delimiters"
	[var="varName"]
	[varStatus="varStatusName"]
	[begin="begin"] [end="end"] [step="step"]>
	
	body content
	
</c:forTokens>

					

For example:


<c:forTokens items="moe,larry,curly" delimiters="," var="stooge">
   <c:out value="${stooge}/><p>
</c:forTokens>

					

URL Related tags.

JSTL provides several tags for handling URLs and accessing Web resources. URLs can be difficult to work with when you must worry about URL rewriting (to insert the session ID when the browser doesn't support cookies), URL encoding of parameters, and referencing resources from a separate servlet context within the same servlet container.

The <c:url> tag formats a URL into a string and stores it into a variable. The <c:url> tag automatically performs URL rewriting when necessary. The var attribute specifies the variable that will contain the formatted URL. The optional scope attribute specifies the scope of the variable (page is the default). The value attribute specifies the URL to be formatted.

Syntax.

Syntax 1: Without body content:


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

					
Syntax 2: With body content to specify query string parameters:

<c:url value="value" [context="context"]
	[var="varName"] [scope="{page|request|session|application}"]>
	
	<c:param> subtags

</c:url>

					
As a security precaution, the URL is only rewritten for relative URLs.

<c:param name="name" value="value" />

					

<c:param name="name">
	parameter value
</c:param>

					

Examples:


<c:url var="trackURL" value="/tracking.html"/>

					

<c:url var="trackURL" value="/track.jsp" context="/tracking"/>

					

<c:url value="/track.jsp" var="trackingURL">
	<c:param name="trackingId" value="1234"/>
	<c:param name="reportType" value="summary"/>
</c:url>

					

The <c:import> tag is similar to the <jsp:import> tag, but it is much more powerful. For example, the <jsp:import> tag usually just imports resources from within the same servlet container. The <jsp:import> tag can import data from other servers as well as from within the same container. Also, the <jsp:import> tag automatically inserts the imported content directly into the JSP. Although the <c:import> tag can automatically insert content, it can also return the content as either a STRING or a READER. The only required attribute in the <c:import> tag is url, which specifies the URL to be imported. As with the <c:url> tag, the URL may be a relative URL, a context-relative URL, or an absolute URL.

Syntax.

Syntax 1: Resource content inlined or exported as a String object:


<c:import url="url" [context="context"]
	[var="varName"] [scope="{page|request|session|application}"]
	[charEncoding="charEncoding"]>
	
	optional body content for <c:param> subtags
	
</c:import>

					
Syntax 2: Resource content exported as a Reader object:
					
<c:import url="url" [context="context"]
	varReader="varReaderName"
	[charEncoding="charEncoding"]>
	
	body content where varReader is consumed by another action
	
</c:import>

					

Examples:


<c:import var="data" url="/data.xml"/>
<c:out value="${data}/>

					
is equivalent to:

<c:import url="/data.xml"/>

					
Using of reader:

<c:import url="/data.xml" varReader="dataReader" scope="session"/>

					

<c:redirect> sends an HTTP redirect to the client.

Syntax.

Syntax 1: Without body content:


<c:redirect url="value" [context="context"] />

					
Syntax 2: With body content to specify query string parameters:

<c:redirect url="value" [context="context"]>
	<c:param> subtags
</c:redirect>

					

Professional hosting     Belorussian informational portal         Free SCBCD 1.3 Study Guide     Free SCDJWS 1.4 Study Guide     SCDJWS 1.4 Quiz     Free IBM Certified Associate Developer Study Guide     Free SCJP 5.0 (Tiger) Study Guide     Free Mock Exam Engine     IBM Test 000-287. Enterprise Application Development with IBM WebSphere Studio, V5.0 Study Guide