JSTL Core Tag LibraryS2C Home « JSTL Core Tag Library

In our first lesson on JSTL tag libraries we look at the Core tag library. The Core tag library consists of fourteen actions which we can group into four seperate areas covering general purpose, conditional, iteration and URL related. We will look at each of these groups and the actions within each, in much more detail, as we work through this lesson.

Each Core action can have mandatory attributes that have to be populated and each attribute may also allow a run-time expression to be used. If a run-time expression is allowed for an attribute this can be populated using a static string or more interestingly a dynamic value which can be an EL or Java expression or a value set using the <jsp:attribute> standard action. If no run-time expression is allowed for an attribute then you can only populate that attribute using a static string.

General Purpose Core ActionsTop

There are four general purpose Core actions, these being <c:set> which allows us to set an attribute within any scope, <c:remove> which allows us to remove an attribute from any scope, <c:out> which allows us to output expressions and template text and <c:catch> which allows us to intercept errors before they propogate up the stack.

Action /
Attribute Name
Mandatory Run-time Expression? Default Value Object Type Description
<c:set>
valueNoYesNoneObjectString to be created, or reference to a scoped object, or new string property value.
varNoNoNoneStringName of scoped variable to be created.
scopeNoNoPageStringScope that the created scoped variable exists in.
targetNoYesNoneObjectA JavaBeans or java.util.Map scoped object to assign a new string property value to.
propertyNoYesNoneStringName of the property to be assigned a new string property value.
<c:remove>
varYesNoNoneStringName of scoped variable to be removed.
scopeNoNoPageStringScope that scoped variable to be removed exists in.
<c:out>
valueYesYesNoneObjectExpression to be evaluated.
escapeXmlNoYestrueBooleanIndicates whether the characters < > & ' and " are escaped to their HTML entity codes
defaultNoYesEmpty stringObjectDefault value.
<c:catch>
varNoNoNoneStringPaged scoped variable representing the exception.

<c:set>Top

The <c:set> tag allows us to create an object in any scope and depending on the form used, of which there are four variants, can be used to do any of the following:

  • Create a scoped object that references a string property value.
  • Create a scoped variable that references an existing scoped object.
  • Modify the string property value of a scoped object.

The following code snippets shows the four variants of the <c:set> tag available where the square brackets indicate optional attributes and the curly bracers indicate a choice of options within them where the default is underlined.


// Create scoped object where value attribute specifes a string property value 
<c:set value="value" var="varName" [scope="{page|request|session|application}"]>

// Create scoped object where value attribute specifes a string property value 
// passed in the body content
<c:set var="varName" [scope="{page|request|session|application}"]>
    specified value
</c:set>

// Modify the string property value of a scoped object 
<c:set target="target" property="propertyName" value="value"">

// Modify the string property value of a scoped object passed in the body content
<c:set target="target" property="propertyName">
    specified value
</c:set>

<c:remove>Top

The <c:remove> tag allows us to remove a scoped variable. The actual object referenced by the scoped variable is not removed so any other scoped variables that access the object can still do so.

The following code snippets shows the syntax of the <c:remove> tag where the square brackets indicate optional attributes and the curly bracers indicate a choice of options within them where the default is underlined.


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

<c:out>Top

The <c:out> tag allows us to evaluate an expression and outputs the results to the current JspWriter and consists of two variants, with or without a body.

The following code snippets shows the two variants of the <c:out> tag where the square brackets indicate optional attributes and the curly bracers indicate a choice of options within them where the default is underlined.


// Evaluate expression and output to current jspWriter
<c:out value="value" default="defaultValue" [escapeXml="{true|false}"]>

// Evaluate expression and output to current jspWriter defaulting to body content
<c:out var="varName" [escapeXml="{true|false}"]>
    default value
</c:out>

<c:catch>Top

The <c:catch> tag allows us to catch an error within a JSP page before it propogates to a JSP error page or up the stack. The exception thrown is Throwable which is right at the top of the exception hierarchy as shown in the Java - Exception Hierarchy Diagram section, so only use the <c:catch> tag for errors you want to deal with within the JSP page itself.

The following code snippets shows the syntax of the <c:catch> tag.


// Catch an error before it propogates to a JSP error page or up the stack
<c:catch var="exceptionNumber">
    exception body
</c:catch>

General Purpose ExamplesTop

The following code shows examples of using general purpose tags within the Core tag library.


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

<%-- Set a scoped object and property in request scope --%>
<c:set var="aVar" value="A stitch in time saves nine!" scope="request">
<%-- Output scoped object property value --%>
<c:out value="${requestScope.aVar}" default="Value not found!"/>
<%-- Remove a reference to a scoped object --%>
<c:remove var="aVar"scope="request">
<%-- Output scoped object property value --%>
<c:out value="${requestScope.aVar}" default="Value not found!"/>
<%-- Catch an exception --%>
<c:catch var="excNo">
   <%
      int num = 0;
      out.write(6/num);
   %>
</c:catch>
<p>Exception message is: ${excNo.message}</p>

The following screnshot shows the results of running the above JSP code.

Core Tags

Conditional Core ActionsTop

There are four conditional Core actions, these being <c:if> action which allows us to process the body content if a condition evaluates to true, the <c:choose> action which works in a similar way to a Java switch statement when used in conjunction with the other two conditional actions; these being the <c:when> action which acts like a Java case statement and the <c:otherwise> action which acts like a Java default statement.

Action /
Attribute Name
Mandatory Run-time Expression? Default Value Object Type Description
<c:if>
testYesYesNoneBooleanTest condition to be tested for.
If true body content is processed.
varNoNoNoneStringName of scoped variable referencing the value of the test condition
scopeNoNoPageStringScope of the scoped variable specified by var.
<c:choose>
The <c:choose> action contains no attributes although the body may contain one or more <c:when> actions and zero or one <c:otherwise> actions
<c:when>
testYesYesNoneBooleanTest condition to be tested for.
If true body content is processed.
<c:otherwise>
No attributes

<c:if>Top

The <c:if> tag allows us to process the body content of the <c:if> tag if a condition evaluates to true and consists of two variants, with or without a body.

The following code snippets shows the two variants of the <c:if> tag where the square brackets indicate optional attributes and the curly bracers indicate a choice of options within them where the default is underlined.


// Evaluate expression and save test condition result to var
<c:if test="testCondition" var="varName" [scope="{page|request|session|application}"]>

// Evaluate expression and optionally save test condition result to var.
// Process body content if condition evaluates to true.
<c:if test="testCondition" [var="varName"] [scope="{page|request|session|application}"]>
    body content to process
</c:if>

<c:choose>Top

The <c:choose> tag is used in conjunction with the <c:when> and <c:otherwise> tags and works in a similar way to the switch .. case .. default Java conditional. There are two variants of the <c:choose> tag as shown in the code snippets below:


// <c:choose> and <c:when> 
<c:choose>
   <c:when test="S{expression to test}">
      expression evaluates to true
   </c:when>
   <c:when test="S{expression to test}">
      expression evaluates to true
   </c:when>
</c:choose>

// <c:choose>  <c:when> and <c:otherwise> 
<c:choose>
   <c:when test="S{expression to test}">
      expression evaluates to true
   </c:when>
   <c:when test="S{expression to test}">
      expression evaluates to true
   </c:when>
   <c:otherwise>
      no expressions have evaluated to true
   </c:otherwise>
</c:choose>

Conditional ExamplesTop

The following code shows examples of using the conditional tags within the Core tag library.


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

<%-- Test an expression and process body if true --%>
<c:if test="${true}">
   <p>Body content activated</p>
</c:if>
<%-- Test a number of expressions --%>
<c:choose>
   <c:when test="${true and false}">
      <p>First when was processed</p>
   </c:when>
   <c:when test="${false}">
      <p>Second when was processed</p>
   </c:when>
   <c:otherwise>
      <p>otherwise was processed</p>
   </c:otherwise>
</c:choose>

The following screnshot shows the results of running the above JSP code.

Core Conditional Tags

Iteration Core ActionsTop

There are two iteration Core actions, these being <c:forEach> action which allows us iterate over a collection of objects or to iterate over the body content of the <c:forEach> tag a set number of times (much like a for loop) and the <c:forTokens> action which allows us to do string tokenisation.

The indexes for the <c:forEach> and <c:forTokens> actions are zero-based.

Action /
Attribute Name
Mandatory Run-time Expression? Default Value Object Type Description
<c:forEach>
varNoNoNoneStringName of scoped variable referencing the current item within the iteration.
itemsNoYesNoneCollection typeCollection of objects to iterate over.
  • String
    • var attribute references comma delimited String object.
  • Array
    • var attribute references declared type of array.
  • Array of primitives
    • var attribute references wrapper type of declared array.
  • java.util.Collection or
    java.util.Enumeration or
    java.util.Iterator
    • var attribute references declared type of item attribute within the collection.
varStatusNoNoNoneStringName of scoped variable holding the status of the iteration which is of type javax.servlet.jsp.jstl.core.LoopTagStatus.
beginNoYesNoneintbegin attribute must be >= 0.
If items attribute specified then iteration begins at object located at specified index.
If items attribute not specified then iteration begins with value set by specified begin attribute.
endNoYesNoneintIf items attribute specified then iteration ends after object located at specified index.
If items attribute not specified then iteration ends at value set by specified end attribute.
stepNoYesNoneintstep attribute must be >= 1.
Iteration will only process every step item within the collection.
<c:forTokens>
varNoNoNoneStringName of scoped variable referencing the current item within the iteration.
itemsYesYesNoneStringThe string of tokens to iterate over.
delimsYesYesNoneStringThe delimiter set.
varStatusNoNoNoneStringName of scoped variable holding the status of the iteration which is of type javax.servlet.jsp.jstl.core.LoopTagStatus.
beginNoYesNoneintbegin attribute must be >= 0.
Iteration begins with value set by specified begin attribute.
endNoYesNoneintIteration ends at value set by specified end attribute.
stepNoYesNoneintstep attribute must be >= 1.
Iteration will only process every step token within the string.

<c:forEach>Top

The <c:forEach> tag allows us to iterate over a collection of objects or to iterate over the body content of the <c:forEach> tag a set number of times (much like a for loop).

We can iterate through a comma delimited String object, an array of objects or array of primitives. We can also iterate over a java.util.Enumeration or java.util.Iterator, as well as all implementations of java.util.Map and java.util.Collection.

The following code snippets shows the two variants of the <c:forEach> tag where the square brackets indicate optional attributes.


// Iterate over a collection of objects
<c:forEach items="collection" ["var="varName"] ["varStatus="varStatusName"] 
           ["begin="begin"] ["end="end"] ["step="step"]> 
    body content
</c:forEach>

// Iterate over the body content (like a for loop)
<c:forEach ["var="varName"] ["begin="begin"] ["end="end"] ["step="step"]> 
    body content
</c:forEach>

<c:forTokens>Top

The <c:forTokens> tag allows us to iterate over a string of tokens that are delimited by the specified delimiters.

The following code snippets shows the syntax of the <c:forTokens> tag where the square brackets indicate optional attributes.


// Iterate over a collection of objects
<c:forTokens items="stringOfTokens" delims="delimiters" "["var="varName"] ["varStatus="varStatusName"] 
           ["begin="begin"] ["end="end"] ["step="step"]> 
    body content
</c:forTokens>

Iteration ExamplesTop

The following code shows an example of using the <c:forEach> iteration tag of the Core tag library.


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

<table>
<%-- Iterate over request headers --%>
   <c:forEach var="reqHeaders" items="${headerValues}"> 
      <tr><th>The Value Of The Header Key</th><th>The Value Of The Header Value</th></tr>
      <tr><td>${reqHeaders.key}</td><td>${reqHeaders.value[0]}</td></tr>
   </c:forEach>
</table>

The following screnshot shows the results of running the above JSP code.

Core Iteration Tags

URL Related Core ActionsTop

There are four URL related Core actions, these being <c:import> action which allows us to include request-time inclusion of other resources, the <c:url> action which generates a URL for page output; the <c:redirect> action which redirects the client to the specified URL and the <c:param> action which is used to attach parameters to the other three URL related actions.

Action /
Attribute Name
Mandatory Run-time Expression? Default Value Object Type Description
<c:import>
urlYesYesNoneStringThe URL of the resource to import.
contextNoYesNoneStringContext name when accessing a relative URL resource belonging to a foreign context.
varNoNoNoneStringExported scoped variable name, with a type of String for the resource’s content.
scopeNoNoPageStringScope of the scoped variable specified by var.
charEncodingNoYesISO-8859-1StringCharacter encoding of the content at input resource.
varReaderNoNoNoneStringExported scoped variable name, with a type of Reader for the resource’s content.
<c:url>
valueNoYesNoneStringThe URL to be processed
contextNoYesNoneStringContext name when accessing a relative URL resource belonging to a foreign context.
varNoNoNoneStringExported scoped variable name, with a type of String for the resource’s content.
scopeNoNoPageStringScope of the scoped variable specified by var.
<c:redirect>
urlYesYesNoneStringThe URL of the resource to redirect to.
contextNoYesNoneStringContext name when accessing a relative URL resource belonging to a foreign context.
<c:param>
nameNoYesNoneStringName of the query string parameter.
valueNoYesNoneStringValue of parameter.

<c:import>Top

The <c:import> tag allows us to import the content of a URL-based resource just like the jsp:include standard action. The difference is that the jsp:include standard action can only import resources from the same application, whereas the <c:import> tag allows us to import URL-based resources from different applications within the same container and even from an external resource outside the container.

The following code snippets shows the two variants of the <c:import> tag where the square brackets indicate optional attributes.


// Resource content inlined or exported as a String object
<c:import url="url" [context="context"] [var="varName"] 
          [scope="{page|request|session|application}"] [charEncoding="charEncoding"]>
    <c:param name="name" value="value">Somevalue</c:param>
</c:import>

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

<c:url>Top

The <c:url> tag allows us to build a URL with the proper rewriting rules applied, generally for reuse as a link within the JSP page.

The following code snippets shows the two variants of the <c:url> tag where the square brackets indicate optional attributes.


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

// With body content to specify query string parameters
<c:url value="value" [context="context"] [var="varName"] 
       [scope="{page|request|session|application}"]>
    <c:param name="name" value="value">Somevalue</c:param>
</c:url>

<c:redirect>Top

The <c:redirect> tag causes the client to redirect to the specified URL. The <c:import> tag allows us to redirect to URL-based resources from different applications within the same container and even to an external resource outside the container

The following code snippets shows the two variants of the <c:redirect> tag where the square brackets indicate optional attributes.


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

// With body content to specify query string parameters
<c:redirect url="value" [context="context"]>
    <c:param name="name" value="value">Somevalue</c:param>
</c:redirect>

URL Related ExamplesTop

The following code shows examples of using the <c:import> tag within the Core tag library.


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

<%-- Import two resources from same application --%>
<c:import url="jstlcore.jsp">
<c:import url="jstlcorecond.jsp">

The following screnshot shows the results of running the above JSP code.

URL Related Tags

Lesson 2 Complete

In our first lesson on JSTL tag libraries we looked at the Core tag library.

What's Next?

In our second lesson on JSTL tag libraries we look at the XML tag library.

go to home page Homepage go to top of page Top