Java Notes
Complete guide to JSP tags including standard actions, JSTL core tags, formatting tags, SQL tags, custom tags, and tag files for building maintainable JSP applications.
Why Use Tags Instead of Scriptlets?
Scriptlets (<% %>) mix Java code with HTML, making pages hard to maintain. JSP tags provide a cleaner, XML-like syntax for common operations.
<%-- ❌ BAD: Scriptlet approach --%>
<%
List<String> items = (List<String>) request.getAttribute("items");
for (String item : items) {
%>
<li><%= item %></li>
<% } %>
<%-- ✅ GOOD: JSTL approach --%>
<c:forEach var="item" items="${items}">
<li>${item}</li>
</c:forEach>JSTL Core Tags (c:)
c:out — Output with Escaping
<%-- Safely outputs value (escapes HTML to prevent XSS) --%>
<c:out value="${user.name}" />
<c:out value="${user.bio}" default="No bio provided" />
<c:out value="${param.search}" escapeXml="true" />c:set — Set Variables
<%-- Set page-scoped variable --%>
<c:set var="siteName" value="WohoTech" />
<c:set var="year" value="2024" scope="session" />
<c:set var="total" value="${price * quantity}" />
<%-- Set bean property --%>
<c:set target="${user}" property="name" value="John" />c:remove — Remove Variables
<c:remove var="tempData" scope="session" />c:if — Conditional
<c:if test="${not empty user}">
<p>Welcome, ${user.name}!</p>
</c:if>
<c:if test="${user.role == 'admin'}">
<a href="/admin">Admin Panel</a>
</c:if>
<c:if test="${sessionScope.cart.size() > 0}">
<p>You have ${sessionScope.cart.size()} items in cart</p>
</c:if>c:choose / c:when / c:otherwise — Switch-like
<c:choose>
<c:when test="${user.role == 'admin'}">
<p>Admin Dashboard</p>
</c:when>
<c:when test="${user.role == 'teacher'}">
<p>Teacher Dashboard</p>
</c:when>
<c:when test="${user.role == 'student'}">
<p>Student Dashboard</p>
</c:when>
<c:otherwise>
<p>Guest View</p>
</c:otherwise>
</c:choose>c:forEach — Loops
<%-- Iterate over collection --%>
<table border="1">
<tr><th>#</th><th>Name</th><th>Email</th><th>Status</th></tr>
<c:forEach var="student" items="${students}" varStatus="status">
<tr class="${status.index % 2 == 0 ? 'even' : 'odd'}">
<td>${status.count}</td>
<td>${student.name}</td>
<td>${student.email}</td>
<td>
<c:choose>
<c:when test="${student.active}">
<span style="color:green">Active</span>
</c:when>
<c:otherwise>
<span style="color:red">Inactive</span>
</c:otherwise>
</c:choose>
</td>
</tr>
</c:forEach>
</table>
<%-- Loop with counter --%>
<c:forEach var="i" begin="1" end="10" step="1">
<p>Number: ${i}</p>
</c:forEach>
<%-- varStatus properties --%>
<%-- status.index (0-based), status.count (1-based) --%>
<%-- status.first, status.last, status.current --%>c:forTokens — Split and Iterate
<c:forTokens var="color" items="red,green,blue,yellow" delims=",">
<span style="color:${color}">${color}</span>
</c:forTokens>c:url and c:param — URL Building
<c:url var="searchUrl" value="/search">
<c:param name="q" value="${query}" />
<c:param name="page" value="1" />
</c:url>
<a href="${searchUrl}">Search</a>
<%-- Output: /search?q=java&page=1 --%>c:redirect — Server Redirect
<c:if test="${empty sessionScope.user}">
<c:redirect url="/login.jsp">
<c:param name="message" value="Please login" />
</c:redirect>
</c:if>c:import — Include External Content
<c:import url="/header.jsp">
<c:param name="title" value="Home Page" />
</c:import>
<%-- Include external URL --%>
<c:import url="https://api.example.com/data" var="apiData" />
<p>API Response: ${apiData}</p>c:catch — Exception Handling
<c:catch var="error">
<% int result = 10 / 0; %>
</c:catch>
<c:if test="${not empty error}">
<p style="color:red">Error: ${error.message}</p>
</c:if>JSTL Formatting Tags (fmt:)
<%@ taglib uri="jakarta.tags.fmt" prefix="fmt" %>
<%-- Format date --%>
<fmt:formatDate value="${now}" pattern="dd-MM-yyyy" />
<fmt:formatDate value="${now}" pattern="hh:mm:ss a" />
<fmt:formatDate value="${now}" type="both" dateStyle="long" timeStyle="short" />
<%-- Format number --%>
<fmt:formatNumber value="${price}" type="currency" currencyCode="INR" />
<fmt:formatNumber value="${percentage}" type="percent" />
<fmt:formatNumber value="${bigNumber}" pattern="#,##,###.##" />
<%-- Parse date --%>
<fmt:parseDate var="parsedDate" value="2024-03-15" pattern="yyyy-MM-dd" />
<%-- Set locale --%>
<fmt:setLocale value="en_IN" />
<%-- Internationalization --%>
<fmt:setBundle basename="messages" />
<fmt:message key="welcome.message" />JSTL Function Tags (fn:)
<%@ taglib uri="jakarta.tags.functions" prefix="fn" %>
<p>Length: ${fn:length(name)}</p>
<p>Upper: ${fn:toUpperCase(name)}</p>
<p>Lower: ${fn:toLowerCase(name)}</p>
<p>Contains: ${fn:contains(email, "@gmail.com")}</p>
<p>Starts with: ${fn:startsWith(url, "https")}</p>
<p>Ends with: ${fn:endsWith(file, ".pdf")}</p>
<p>Substring: ${fn:substring(name, 0, 5)}</p>
<p>Replace: ${fn:replace(text, " ", "-")}</p>
<p>Split: ${fn:split(csv, ",")}</p>
<p>Join: ${fn:join(array, ", ")}</p>
<p>Trim: ${fn:trim(input)}</p>
<p>Index: ${fn:indexOf(text, "world")}</p>
<p>Escaped: ${fn:escapeXml(htmlContent)}</p>JSP Standard Action Tags
<%-- Include page at request time --%>
<jsp:include page="sidebar.jsp" flush="true">
<jsp:param name="section" value="news" />
</jsp:include>
<%-- Forward request --%>
<jsp:forward page="error.jsp">
<jsp:param name="code" value="404" />
</jsp:forward>
<%-- JavaBean usage --%>
<jsp:useBean id="student" class="com.example.Student" scope="request" />
<jsp:setProperty name="student" property="name" param="name" />
<jsp:setProperty name="student" property="*" /> <%-- auto-set all matching params --%>
Name: <jsp:getProperty name="student" property="name" />
Email: <jsp:getProperty name="student" property="email" />Custom Tag Library
Tag Handler Class
package com.example.tags;
import jakarta.servlet.jsp.*;
import jakarta.servlet.jsp.tagext.*;
import java.io.*;
public class GreetingTag extends SimpleTagSupport {
private String name;
private String style;
public void setName(String name) { this.name = name; }
public void setStyle(String style) { this.style = style; }
@Override
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
String greeting;
int hour = java.time.LocalTime.now().getHour();
if (hour < 12) greeting = "Good Morning";
else if (hour < 17) greeting = "Good Afternoon";
else greeting = "Good Evening";
out.println("<div class=\"" + (style != null ? style : "greeting") + "\">");
out.println("<h3>" + greeting + ", " + name + "!</h3>");
out.println("</div>");
}
}Tag Library Descriptor (TLD)
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="https://jakarta.ee/xml/ns/jakartaee" version="3.0">
<tlib-version>1.0</tlib-version>
<short-name>myTags</short-name>
<uri>http://example.com/mytags</uri>
<tag>
<name>greeting</name>
<tag-class>com.example.tags.GreetingTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>style</name>
<required>false</required>
</attribute>
</tag>
</taglib>Using Custom Tag
<%@ taglib uri="http://example.com/mytags" prefix="my" %>
<my:greeting name="${user.name}" style="welcome-box" />Tag Summary Table
| Tag Category | Prefix | Purpose |
|---|---|---|
| Core | c: | Variables, conditions, loops, URLs |
| Formatting | fmt: | Dates, numbers, i18n |
| Functions | fn: | String manipulation |
| SQL | sql: | Database queries (avoid in production) |
| XML | x: | XML processing |
| Custom | your: | Your own tag libraries |
Interview Key Points
- JSTL replaces scriptlets for cleaner JSP pages
<c:forEach>is the most commonly used JSTL tag<c:out>escapes HTML by default (XSS prevention)${expr}is Expression Language (EL), not JSTL- JSTL requires a JAR file in WEB-INF/lib
- Custom tags extend
SimpleTagSupportorTagSupport - TLD file defines tag attributes and classes
Summary
In this chapter, we learned about JSP Tags and JSTL in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JSP Tags and JSTL.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, servlets, jsp, tags
Related Java Master Course Topics