Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

JSTL Core Tag Library: Simplifying Java Web Development

Tech 2

Introduction to JSTL

Why Learn JSTL?

Even with EL expressions available in JSP to retrieve data from scoped objects, developers often find themselves embedding Java code directly within JSP pages. This approach leads to several issues:

  • Complexity: Mixing Java code with HTML makes pages harder to read
  • Error-Prone: Manual Java coding encreases the likelihood of errors
  • Maintenance Challenges: Code becomes difficult to maintain and update

What is JSTL?

JSTL (JavaServer Pages Standard Tag Library) is a collection of useful JSP tags that encapsulate core functionality common to many JSP applications. Developed by the Java Community Process (JCP) and maintained by the Apache Jakarta project, JSTL provides a standardized way to implement common tasks without writing Java code directly in JSP pages.

Benefits of Using JSTL

  • Improved Readability: Replaces Java code with clean, readable tags
  • Enhanced Maintainability: Separates presentation logic from business logic
  • Increased Productivity: Reduces development time with reusable components
  • Standardization: Provides a consistent approach across projects

JSTL Tag Library Components

JSTL is organized into several functional areas:

  • Core Tag Library: core (prefix: c)
  • Formatting Tag Library: format (prefix: fmt)
  • Function Tag Library: function (prefix: fn)

Prerequisites for Using JSTL

  1. Add JSTL JAR: Include jstl-1.2.jar in your project's classpath
  2. Taglib Directive: Declare the tag library in your JSP page using the taglib directive

Importing the Core Tag Library

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

Scope Management Tags

These tags provide functionality similar to Java's scoped attribute methods:

  • <c:set>: Stores data in specified scope (equivalent to setAttribute())
  • <c:out>: Retrieves data from scope (equivalent to getAttribute())
  • <c:remove>: Removes data from scope (equivalent to removeAttribute())

Example: Scope Management

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Scope Management Example</title>
</head>
<body>
    <%-- Store data in different scopes --%>
    <c:set scope="page" var="message" value="Page Scope Message"/>
    <c:set scope="request" var="message" value="Request Scope Message"/>
    <c:set scope="session" var="message" value="Session Scope Message"/>
    <c:set scope="application" var="message" value="Application Scope Message"/>

    <%-- Remove data from specific scopes --%>
    <c:remove var="message" scope="session"/>
    <c:remove var="message" scope="application"/>

    <hr/>
    <%-- Retrieve using EL expressions --%>
    Page Scope: ${pageScope.message}<br/>
    Request Scope: ${requestScope.message}<br/>
    Session Scope: ${sessionScope.message}<br/>
    Application Scope: ${applicationScope.message}<br/>

    <hr/>
    <%-- Retrieve using c:out with default values --%>
    <c:out value="${pageScope.message}" default="Page message not available"/><br/>
    <c:out value="${requestScope.message}" default="Request message not available"/><br/>
    <c:out value="${sessionScope.message}" default="Session message not available"/><br/>
    <c:out value="${applicationScope.message}" default="Application message not available"/>
</body>
</html>

Conditional Processing Tags

Using <c:if> and <c:choose>

<%@ page import="java.util.Random" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Conditional Processing Example</title>
</head>
<body>
    <%--
    Generate random score 0-100
    >=90: A
    >=80: B
    >=70: C
    >=60: D
    <60:  E
    --%>
    <%
        int randomScore = new Random().nextInt(101);
        pageContext.setAttribute("studentScore", randomScore);
    %>

    Score: ${studentScore}<br/> Grade:
    
    <%-- Using c:if --%>
    <c:if test="${studentScore ge 90}" scope="page" var="gradeA">A</c:if>
    <c:if test="${studentScore ge 80 and studentScore lt 90}" scope="page" var="gradeB">B</c:if>
    <c:if test="${studentScore ge 70 and studentScore lt 80}" scope="page" var="gradeC">C</c:if>
    <c:if test="${studentScore ge 60 and studentScore lt 70}" scope="page" var="gradeD">D</c:if>
    <c:if test="${studentScore lt 60}" scope="page" var="gradeE">E</c:if>

    <hr/>
    <%-- Check if passing --%>
    <c:if test="${studentScore ge 60}" scope="page" var="isPassing">Passing</c:if>
    <c:if test="${!pageScope.isPassing}">Failing</c:if>

    <hr/>
    <%-- Using c:choose for cleaner multi-way branching --%>
    <c:choose>
        <c:when test="${studentScore ge 90}">A</c:when>
        <c:when test="${studentScore ge 80}">B</c:when>
        <c:when test="${studentScore ge 70}">C</c:when>
        <c:when test="${studentScore ge 60}">D</c:when>
        <c:otherwise>E</c:otherwise>
    </c:choose>
</body>
</html>

Iteration Tags

Multiplication Table Example

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Multiplication Table</title>
</head>
<body>
    <%--
    Equivalent to:
    for (int row = 1; row <= 9; row++) {
        for (int col = 1; col <= row; col++) {
            // Display multiplication
        }
    }
    --%>
    <c:forEach var="row" begin="1" end="9" step="1">
        <c:forEach var="column" begin="1" end="${row}" step="1">
            ${column} × ${row} = ${row * column} &nbsp;
        </c:forEach>
        <br/>
    </c:forEach>
</body>
</html>

Collection Iteration Example

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Employee List</title>
    <style>
        .data-table {
            border: 2px solid #0066cc;
            width: 95%;
            margin: 20px auto;
            border-collapse: collapse;
        }
        .data-table th, .data-table td {
            border: 1px solid #009933;
            padding: 8px;
            text-align: center;
        }
        .data-table th {
            background-color: #f0f8ff;
        }
    </style>
</head>
<body>
    <table class="data-table">
        <tr>
            <th>#</th>
            <th>Index</th>
            <th>First?</th>
            <th>Last?</th>
            <th>Employee ID</th>
            <th>Name</th>
            <th>Manager ID</th>
            <th>Position</th>
            <th>Hire Date</th>
            <th>Salary</th>
            <th>Commission</th>
            <th>Department</th>
            <th>Salary Grade</th>
        </tr>
        
        <%--
        Iterate through employee list
        Attributes:
        - items: Collection to iterate (using EL expression)
        - var: Variable name for current item
        - varStatus: Status object with iteration information
            * count: Current iteration count (1-based)
            * index: Current index (0-based)
            * first: Boolean for first iteration
            * last: Boolean for last iteration
            * current: Current item reference
        --%>
        <c:forEach items="${employeeList}" var="employee" varStatus="status">
            <tr>
                <td>${status.count}</td>
                <td>${status.index}</td>
                <td>${status.first}</td>
                <td>${status.last}</td>
                <td>${employee.id}</td>
                <td>${employee.name}</td>
                <td>${employee.managerId}</td>
                <td>${employee.position}</td>
                <td>${employee.hireDate}</td>
                <td>${employee.salary}</td>
                <td>${employee.commission}</td>
                <td>${employee.departmentId}</td>
                <td>
                    <%-- Determine salary grade --%>
                    <c:choose>
                        <c:when test="${employee.salary <= 500}">A</c:when>
                        <c:when test="${employee.salary <= 1000}">B</c:when>
                        <c:when test="${employee.salary <= 1500}">C</c:when>
                        <c:when test="${employee.salary <= 2000}">D</c:when>
                        <c:when test="${employee.salary <= 3000}">E</c:when>
                        <c:when test="${employee.salary <= 4000}">F</c:when>
                        <c:when test="${employee.salary > 4000}">G</c:when>
                    </c:choose>
                </td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

Key Attributes for <c:forEach>

  • var: Iteration variable name (stored in pageContext scope)
  • begin: Starting value for iteration
  • end: Ending value for iteration
  • step: Increment value for each iteration
  • items: Collection to iterate over (using EL expression)
  • varStatus: Status object providing iteration information:
    • index: Current index (0-based)
    • count: Current count (1-based)
    • first: Boolean indicating first iteration
    • last: Boolean indicating last iteration
    • current: Reference to current iteration object

Conclusion

The JSTL Core Tag Library provides powerful tools for Java web developers to create cleaner, more maintainable JSP pages. By replacing embedded Java code with standardized tags, developers can improve code readability, reduce errors, and enhance application maintainability. The core functionality covered in this article—scope management, conditional processing, and iteration—forms the foundation for effective JSP development using JSTL.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.