JSP and JSTL

The JSP Standard Taglibrary (JSTL) encapsulates as simple tags, several core functionalities common to many JSP applications. For example it contains tags for store / display variables, make iterations, XML manipulation, Input / Output, and so on.

This post explain how to setup a page with JSTL and make some examples for common tags.

Install JSTL

To use a tag library you need to import jar libraries containing the implementation and define tags that invoke functions inside the library.

You can find jstl-1.2.jar on the web or from this local archive.

Test JSTL

Since the jat we’ve copied contains both libraries and TLD definitions, we can start to use JSTL tags. To use them, first we need reference JSTL with a declaration at top of JSP. In the shippet below we reference the jstl/core library, whose tags are available under the prefix “c:” .

<!-- declare usage of common -->
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Then we could put some JSTL tags inside the page.

<h1>Test JSTL</h1>
<!-- import an xml file in a variable, then prints out to page -->
<c:import url="test.xml" var="xml"/>
1. <c:out value="${xml}"/><br/>
2. <c:out value="${xml}" escapeXml="false"/><br/>

In the snippet above we used

  • c:import to read a file on the server, and store content inside a varuable
  • c:out to output the content of a variable to the page (you could escape xml)

See the screenshoot

To make some further test with the jstl/core we insert another two snippet, for loops. The first show a simple loop that build a table

<table border="1">
<tr>
		<th>i:</th>
		<c:forEach var="i" begin="1" end="10" step="1">
			<td><c:out value="${i}"/></td>
		</c:forEach>
	</tr>
</table>

The second list page parameters. Take care that param is an implicit Map object.

<ul>
	<c:forEach var="pageParameters" items="${param}">
		<li><c:out value="${pageParameters.key}"/> =
			<c:out value="${pageParameters.value}"/></li>
	</c:forEach>
</ul>

The result, obvious, are a table and a list. But instead to watch the picture,  you can build yourself.

Enjoy.

References