JSTL stands for JavaServer Pages Standard Tag Library.
✅ It’s a collection of ready-to-use, standardized custom tags for common tasks you often need in JSP, like:
- Iterating over collections
- Making decisions (if/else)
- Formatting text and numbers
- Accessing databases
- Handling XML
It replaces the need to write Java code (<% %>
) inside JSPs for most standard operations, making your pages cleaner, faster to develop, and easier to maintain.
🎯 Purpose of JSTL
➔ Make JSP pages declarative (based on tags),
➔ Avoid Java scriptlets inside JSP,
➔ Help developers focus on presentation, not backend logic.
🔥 What Does JSTL Provide? (Main Libraries)
Library | Purpose | Tag Prefix Example |
---|---|---|
Core | Common tasks (if, loops, setting variables) | <c:if> , <c:forEach> |
Formatting | Format numbers, dates, currencies | <fmt:formatNumber> , <fmt:formatDate> |
SQL | Simple database operations (for prototyping only) | <sql:query> , <sql:update> |
XML | XML document manipulation | <x:parse> , <x:out> |
Functions | Common functions for strings and collections | ${fn:toUpperCase(str)} |
🔵 Common JSTL Core Tags
Tag | Purpose |
---|---|
<c:if> | Conditional logic (if) |
<c:choose> , <c:when> , <c:otherwise> | Switch-case logic |
<c:forEach> | Looping over arrays, collections, maps |
<c:set> | Set a variable (attribute) |
<c:remove> | Remove a variable |
<c:import> | Import content from a URL |
<c:redirect> | Redirect to another page |
🛠️ How to Use JSTL in a JSP
- Add JSTL library to your project.
- If you use Maven:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
Otherwise, you need to place the jstl.jar
and standard.jar
files in /WEB-INF/lib/
.
2. Declare the taglib at the top of your JSP page.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Now you can use tags like <c:if>
, <c:forEach>
, etc.
🧠 Small Example Using JSTL
Example: Showing a user list
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach var="user" items="${userList}">
<p>User: ${user.name}</p>
</c:forEach>
Here, userList
is a collection (list) passed from a servlet or controller.
No Java code (<% %>
) is needed in the JSP!
📢 Why is JSTL Important?
Benefit | Why It Matters |
---|---|
Cleaner JSP code | No need for scriptlets (<% %> ) |
Better separation | Presentation (JSP) separated from logic (Java classes) |
Easier for designers | Non-Java people can work with JSP pages too |
Reusability | Tags are reusable across many pages |
Standardization | JSTL is standardized and portable across servers |
🎯 Quick Final Summary:
Term | Meaning |
---|---|
JSTL | Standard set of ready-to-use tags for common tasks in JSP |
Goal | Cleaner, declarative, maintainable JSP pages |
Common Tags | <c:if> , <c:forEach> , <fmt:formatDate> , etc. |