CACS354 Advance Java Programming

Advance Java ProgrammingUnit 212 min read

JSP Scripting Elements & Directives: Tags, Beans, and Dynamic Content

Unit 2 of Advance Java Programming demystifies JSP’s scripting tools (scriptlets, expressions, declarations) and directives (page, include, taglib), showing how they embed logic, reuse components, and control page behavior—with real-world ties to eSewa’s dynamic forms and Daraz’s checkout logic.

TAKEAWAYS

  • JSP scriptlets (<% ... %>) embed Java logic but are deprecated in favor of expressions/declarations.
  • Expressions (<%= ... %>) output dynamic content (e.g., <%= sum %>) but cannot modify variables.
  • Declarations (<%! ... %>) define methods/variables for reuse across requests (e.g., helper functions).
  • Directives (<%@ ... %>) configure JSP pages globally (e.g., page encoding="UTF-8" or include static files).
  • JavaBeans (<%@ page isELIgnored="false" %>) enable component-based UI with properties/methods (e.g., Daraz’s cart system).
  • EL (Expression Language) (${bean.property}) simplifies data binding (e.g., Pathao’s fare calculator).

1. JSP Scripting Elements: Logic vs. Presentation

JSP blends HTML with Java logic using three scripting tags, each serving distinct roles. Below is a comparison table with visual traces of their behavior.

Scriptlet0Expression1Declaration2
MVC Violation Spectrum: Scriptlets (left) are worst, Declarations (right) are best

1.1 Scriptlet Tag (<% ... %>)

  • Purpose: Embeds multi-line Java code (e.g., loops, conditionals) directly in JSP.
  • Example Use: Processing form inputs, validating data.
  • Disadvantage: Deprecated (mixes logic with markup; violates MVC).
flowchart TD
    A["JSP Page with Scriptlet"]
    B["Java Code Executes: `for (int i=0; i<3; i++) {`"]
    C["Loop Iteration 1: i=0"]
    D["Loop Iteration 2: i=1"]
    E["Loop Iteration 3: i=2"]
    F["Output: `<p>Count: 3</p>`"]
    A --> B
    B --> C
    C --> D
    D --> E
    E --> F
    F -->|"MVC Violation"| G["Browser Renders HTML"]
Scriptlet execution flow for a loop (factorial calculation example)
592TOP
Stack state after evaluating `<% int sum = 5 + 9; %>` (push 5, push 9, then push 2)
flowchart TD
    A["JSP Page"] -->|"Scriptlet (`<% ... %>`)"| B["Java Code Executes"]
    B --> C["Output to HTML"]
    C --> D["Browser Renders: Deprecated (MVC Violation)"]

Example: Factorial Calculation (Servlet vs. JSP) Past exam question: Create a JSP page to compute factorial using a scriptlet.

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head><title>Factorial with Scriptlet</title></head>
<body>
    <form action="factorial.jsp" method="get">
        Enter n: <input type="number" name="n"><br>
        <input type="submit" value="Compute">
    </form>
    <%!
        // Declaration (reusable method)
        int factorial(int num) {
            int result = 1;
            for (int i = 2; i <= num; i++) result *= i;
            return result;
        }
    %>
    <% int n = Integer.parseInt(request.getParameter("n")); %>
    <% if (n >= 0) { %>
        Factorial of <%= n %> is <%= factorial(n) %>.
    <% } else { %>
        Invalid input!
    <% } %>
</body>
</html>

Trace Table (Scriptlet Execution):

Step request.getParameter("n") factorial(n) Output
Input n=5 "5" 120 Factorial of 5 is 120.
Input n=-3 "-3" Error Invalid input!

1.2 Expression Tag (<%= ... %>)

  • Purpose: Outputs single Java expressions (no statements) to HTML.
  • Limitations:
    • Cannot declare variables or use loops/conditionals.
    • Only evaluates once per request (not reusable like declarations).

Example: Dynamic Greeting

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
    <h1>Welcome, <%= request.getParameter("name") %>!</h1>
</body>
</html>

Input: name=Alice → Output: <h1>Welcome, Alice!</h1>


1.3 Declaration Tag (<%! ... %>)

  • Purpose: Defines methods/variables reusable across requests (like a helper class).
  • Advantage: Encapsulates logic, improving maintainability.
105153720
Binary Search Tree (BST) after inserting values [10, 5, 15, 3, 7, 20] (highlighted node is the last insertion)

Example: Greatest of Three Numbers

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
    <form action="greatest.jsp" method="get">
        A: <input type="number" name="a"><br>
        B: <input type="number" name="b"><br>
        C: <input type="number" name="c"><br>
        <input type="submit" value="Find Greatest">
    </form>
    <%!
        int max(int a, int b, int c) {
            return Math.max(Math.max(a, b), c);
        }
    %>
    <% int a = Integer.parseInt(request.getParameter("a")); %>
    <% int b = Integer.parseInt(request.getParameter("b")); %>
    <% int c = Integer.parseInt(request.getParameter("c")); %>
    Greatest number: <%= max(a, b, c) %>
</body>
</html>

Trace:

Input (a=10, b=20, c=15) max(10, 20, 15) Output
20 Greatest number: 20

2. JSP Directives: Page Configuration

Directives (<%@ ... %>) configure the JSP page globally, not per request. Key directives:

2.1 page Directive

  • Sets encoding, error pages, session timeout, etc.
  • Example: Force UTF-8 encoding for Nepali text.
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    

2.2 include Directive

  • Statically includes files (e.g., headers, footers) at compile time.
  • Syntax:
    <%@ include file="header.html" %>
    
  • Use Case: Reusable UI components (e.g., Daraz’s checkout footer).

2.3 taglib Directive

  • Enables custom tags (e.g., <c:forEach> from JSTL).
  • Example:
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <c:forEach var="item" items="${cart}">
        ${item.name} - ${item.price}
    </c:forEach>
    

3. JavaBeans in JSP: Component-Based UI

JavaBeans are POJOs (Plain Old Java Objects) with:

  • Public getter/setter methods.
  • No-arg constructor.
  • Used in JSP with EL (Expression Language).
classDiagram
    class UserBean {
        +String username
        +String password
        +String getUsername() String
        +void setUsername(String)
        +String getPassword() String
        +void setPassword(String)
    }
    JSPPage "1"--"uses" UserBean : "<% UserBean user = new UserBean(); %>"
    UserBean "1"--"binds to" EL : "${user.username}"
JavaBean class diagram and its binding to JSP EL (eSewa login example)

Example: User Authentication (Past Exam Question)

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page isELIgnored="false" %> <!-- Enable EL -->
<html>
<body>
    <form action="login.jsp" method="post">
        Username: <input type="text" name="username"><br>
        Password: <input type="password" name="password"><br>
        <input type="submit" value="Login">
    </form>
    <%!
        // JavaBean class (User.java)
        class User {
            private String username;
            private String password;
            public String getUsername() { return username; }
            public void setUsername(String username) { this.username = username; }
            // ... getPassword(), setPassword()
        }
    %>
    <%@ page import="com.example.User" %>
    <% User user = new User(); %>
    <% user.setUsername(request.getParameter("username")); %>
    <% user.setPassword(request.getParameter("password")); %>
    <% if (user.getUsername().equals("admin") && user.getPassword().equals("123")) { %>
        <h1>Welcome, <%= user.getUsername() %>!</h1>
    <% } else { %>
        <p>Invalid credentials.</p>
    <% } %>
</body>
</html>

Real-World Tie: eSewa’s Login

  • Idea Used: JavaBeans model user credentials (username, password) and validate them via EL.
  • Why It Matters: Separates UI (JSP) from logic (JavaBean), following MVC.

4. Expression Language (EL) and Implicit Objects

EL (${...}) simplifies data access using implicit objects:

Object Purpose Example Usage
request HTTP request attributes ${param.username}
session Session-scoped data ${sessionScope.cart}
application Global application data ${appConfig.taxRate}
pageContext Page-specific context ${pageContext.request}

Example: Pathao Fare Calculator

Distance: <input type="number" name="distance" id="distance"><br>
Fare: ${distance * 10} NPR
  • How It Works: EL binds distance from the form to the fare calculation.

5. Comparison: JSP vs. Servlets

Feature JSP Servlet
Purpose Presentation (HTML + logic) Logic (pure Java)
Extends javax.servlet.jsp.JspPage HttpServlet
Scripting Supports <% ... %> tags No built-in scripting
Performance Slower (compiled to Java) Faster (direct bytecode)
Use Case Dynamic UI (e.g., Daraz checkout) Backend processing (e.g., order validation)
1234JSPServletModelViewController
Typical MVC flow: Servlets handle logic, JSPs handle presentation

Example: Same Factorial in Servlet vs. JSP

  • Servlet (pure Java):
    protected void doGet(HttpServletRequest req, HttpServletResponse res) {
        int n = Integer.parseInt(req.getParameter("n"));
        int result = 1;
        for (int i = 2; i <= n; i++) result *= i;
        res.getWriter().write("Factorial: " + result);
    }
    
  • JSP (mixed HTML/Java):
    <%@ page contentType="text/html" %>
    <html>
        <body>
            <% int n = Integer.parseInt(request.getParameter("n")); %>
            Factorial: <%= factorial(n) %>
        </body>
    </html>
    

In the Real World

  1. eSewa’s Dynamic Forms

    • Idea: Uses JSP expressions (<%= balance %>) to display user balances in real time.
    • Why: EL binds database values (e.g., ${user.balance}) to the UI without scriptlets.
  2. Daraz’s Checkout Queue

    • Idea: JavaBeans model cart items (CartItem class) and EL iterates over them:
      <c:forEach var="item" items="${cart.items}">
          ${item.name} - ${item.quantity} x ${item.price}
      </c:forEach>
      
    • Worked Example: If cart.items = [Book, Mobile], the loop renders:
      Book - 1 x 150
      Mobile - 1 x 5000
      
  3. NTC’s Traffic Route Planner

    • Idea: JSP directives (<%@ include file="map.html" %>) embed static route maps while scriptlets calculate shortest paths (e.g., Dijkstra’s algorithm in Java).
    • Real Tie: The map.html includes dynamic waypoints via ${route.waypoints}.

Exam Tip

  • Focus Areas:
    1. Differentiate scriptlet/expression/declaration tags (table format).
    2. Code a JSP page with directives + JavaBeans (e.g., login form).
    3. Explain EL with implicit objects (${param.x} vs. ${sessionScope.x}).
    4. Compare JSP vs. Servlets (table + example).
  • Common Pitfalls:
    • Using scriptlets for complex logic (prefer declarations or servlets).
    • Forgetting <%@ page isELIgnored="false" %> for EL in JavaBeans.
    • Mixing static includes (<%@ include %>) with dynamic ones (<jsp:include>).
  • Past Exam Pattern:
    • 60%: Coding (JSP page with tags/directives).
    • 30%: Theory (differences, EL usage).
    • 10%: Short notes (e.g., "Declaration tag in JSP").

Visual Summary:

mindmap
  root((JSP Scripting Elements))
    Scriptlet
      - Multi-line Java
      - Deprecated
      - Example: Factorial loop
    Expression
      - Single output (`<%= ... %>`)
      - No logic, no reuse
    Declaration
      - Reusable methods (`<%! ... %>`)
      - Example: `max(a, b, c)`
    Directives
      - `page`, `include`, `taglib`
      - Configure globally
    JavaBeans + EL
      - POJOs + `${bean.property}`
      - Example: User authentication

Based on the TU BCA syllabus for Advance Java Programming (CACS354), unit 2.

Discussion

Loading…