JSP Directives and JSTL
Harry
· 11 Sep 2026
· 9 views
JSP Directives and JSTL
Directives configure the JSP page at compile time. JSTL (JSP Standard Tag Library) provides reusable tags for common tasks like loops, conditionals, and formatting. Together they make JSP far more practical.
The Three Directives
page directive configures page attributes:
<%@ page import="java.util.List" %>
<%@ page errorPage="/error.jsp" %>
<%@ page session="true" %>
include directive pulls in another file at compile time:
<%@ include file="/WEB-INF/fragments/header.jsp" %>
taglib directive declares a tag library:
<%@ taglib uri="jakarta.tags.core" prefix="c" %>
<%@ taglib uri="jakarta.tags.fmt" prefix="fmt" %>
Core JSTL Tags
The c: prefix gives you the most used tags:
<%@ taglib uri="jakarta.tags.core" prefix="c" %>
<%-- Conditionals --%>
<c:if test="${not empty user}">
<p>Welcome back, ${user.name}!</p>
</c:if>
<c:choose>
<c:when test="${role == 'admin'}">
<p>Admin dashboard</p>
</c:when>
<c:otherwise>
<p>User dashboard</p>
</c:otherwise>
</c:choose>
<%-- Loops --%>
<c:forEach items="${products}" var="product" varStatus="loop">
<p>${loop.index + 1}. ${product.name} - $${product.price}</p>
</c:forEach>
Formatting Tags
The fmt: prefix handles dates and numbers:
<%@ taglib uri="jakarta.tags.fmt" prefix="fmt" %>
<p>Date: <fmt:formatDate value="${order.date}" pattern="yyyy-MM-dd"/></p>
<p>Price: <fmt:formatNumber value="${product.price}" type="currency"/></p>
Why JSTL Matters
JSTL eliminates scriptlets. Your JSP pages become pure HTML with tag-based logic. They are easier to read, easier to test, and easier for designers to work with.
Key Points
- The
pagedirective sets page-level configuration like imports and error pages. - The
taglibdirective declares JSTL or custom tag libraries. c:if,c:choose, andc:forEachreplace scriptlet logic.fmt:tags handle date and number formatting.- JSTL keeps JSP pages clean and separation of concerns intact.