805 OCPJP 6 Questions 788 SCJP 5 questions 650 OCPJWCD 5 questions 600 OCAJP 7 questions 610 OCPJP 7 questions 510 Upgrade to OCPJP 7 questions 900 Java J2EE Qns


SCWCD : Building JSP Pages Using Tag Libraries

For a custom tag library or a library of Tag Files, create the 'taglib' directive for a JSP page.

The set of significant tags a JSP container interprets can be extended through a tag library.

The taglib directive in a JSP page declares that the page uses a tag library, uniquely identifies the tag library using a URI and associates a tag prefix that will distinguish usage of the actions in the library.

If a JSP container implementation cannot locate a tag library description, a fatal translation error shall result.

It is a fatal translation error for the taglib directive to appear after actions or functions using the prefix.

In the following example, a tag library is introduced and made available to this page using the super prefix; no other tag libraries should be introduced in this page using this prefix. In this particular case, we assume the tag library includes a doMagic element type, which is used within the page.

<%@ taglib uri="http://www.mycorp/supertags" prefix="super" %>




<%@ taglib ( uri="tagLibraryURI" | tagdir="tagDir" ) prefix="tagPrefix" %>


Table 9.1. taglib Directive attributes

uri Either an absolute URI or a relative URI specification that uniquely identifies the tag library descriptor associated with this prefix. The URI is used to locate a description of the tag library.
tagdir Indicates this prefix is to be used to identify tag extensions installed in the /WEB-INF/tags/ directory or a subdirectory. An implicit tag library descriptor is used. A translation error must occur if the value does not start with /WEB-INF/tags/. A translation error must occur if the value does not point to a directory that exists. A translation error must occur if used in conjunction with the uri attribute.
prefix Defines the prefix string in <prefix:tagname> that is used to distinguish a custom action, e.g <myPrefix:myTag>. Prefixes starting with jsp:, jspx:, java:, javax:, servlet:, sun:, and sunw: ARE RESERVED. A prefix must follow the naming convention specified in the XML namespaces specification. Empty prefixes are illegal in this version of the specification, and must result in a translation error.

A fatal translation-time error will result if the JSP page translator encounters a tag with name prefix:Name using a prefix that is introduced using the taglib directive, and Name is not recognized by the corresponding tag library.

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:



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



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


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.


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

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: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 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

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


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).


<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!

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


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)


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>.


	body content (<when> and <otherwise> subtags)


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


	conditional block


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:

	<c:forEach var="customer" items="${customers}">


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 1: Iterate over a collection of objects:

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

Syntax 2: Iterate a fixed number of times:

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

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.


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


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


<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).


<c:forTokens items="stringOfTokens" delims="delimiters"
	[begin="begin"] [end="end"] [step="step"]>
	body content


For example:

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


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 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


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: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"/>


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 1: Resource content inlined or exported as a String object:

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

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



<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 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


scjp 1.5 | scjp 1.6 | scwcd 1.5
Java Certifications