JP
BCA-5002: Unit V
JSP Architecture & Elements
🏠
Subject: BCA-5002 ⭐ 9 Implicit Objects & Lifecycle Day 5 Priority

Unit V: Java Server Pages (JSP)

JSP Architecture, Lifecycle Translation into Servlets, Scripting Elements (Scriptlets, Expressions, Declarations), the 9 Implicit Objects, and JSP vs Servlet.

1. JSP Architecture & Translation Lifecycle
⭐ CSJMU PYQs: 2024–25, 2022, 2019, 2017 (JSP lifecycle translation, jspInit vs _jspService — 10-Mark Core Theory)
🎯 Learning Objectives:
  • Understand how the Web Container translates and compiles a .jsp page into a Java Servlet.
  • Trace the three core lifecycle hooks: jspInit(), _jspService(), jspDestroy().
  • Contrast runtime request handling with compilation-time translation.
💡 Conceptual Intuition: Why Did Sun Microsystems Create JSP When Servlets Already Existed?
In pure Servlets, web developers had to write HTML tags inside long, awkward Java print statements: out.println("<table><tr><td>" + data + "</td></tr></table>");. This was painful to maintain, and frontend designers could not work on the UI without breaking Java code!
JavaServer Pages (JSP) reversed this paradigm: write standard HTML, CSS, and JavaScript freely, and embed dynamic Java code inside special tags (<% ... %>). Under the hood, the web server translates the entire JSP into a high-performance Java Servlet automatically!
⚡ Essential Pass Content
1. Client Requests Page (mypage.jsp) 2. Translation (JSP → Servlet .java) & Compilation (.class) [Performed ONLY on first request or if .jsp was modified] 3. Class Loading, Instantiation & jspInit() [Called Once] 4. _jspService(request, response) [Called per Request] Dispatches worker thread; executes scriptlets & generates HTML 5. jspDestroy() [Called Once upon Server Shutdown]
The Complete 5-Stage JavaServer Pages (JSP) Lifecycle

The Lifecycle Methods in Detail:

  1. public void jspInit(): Invoked by the web container strictly once when the translated servlet instance is initialized. Developers can override this method to open database connections or read configuration parameters.
  2. public void _jspService(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException: Invoked for every incoming client HTTP request by an allocated container worker thread. Critical Rule: Developers cannot override _jspService() because the JSP engine generates its method body automatically from the HTML and scriptlet tags!
  3. public void jspDestroy(): Invoked by the container strictly once when the application is undeployed or the server shuts down, allowing cleanup of persistent resources.
2. JSP vs Servlets (MVC Architecture Role)
⭐ CSJMU PYQs: 2024–25, 2021, 2018 (When to use JSP vs Servlet in enterprise web apps — 10-Mark Question!)
⚡ Essential Pass Content
Evaluation Parameter Java Servlets JavaServer Pages (JSP)
Core Nature HTML embedded inside Java code using out.println() statements. Java code embedded inside standard HTML/CSS markup using special tags.
Primary Role in MVC Controller: Handles HTTP requests, session logic, authentication, and database routing. View: Renders dynamic presentations, layouts, tables, and user interfaces.
Modification & Deployment Any code change requires explicit recompilation and web application redeployment. Changes to .jsp files are automatically re-translated and compiled by the container on the fly!
Developer Suitability Best suited for backend Java software engineers; difficult for UI designers to touch. Ideal for frontend web designers who can format HTML/CSS without deep Java expertise.
Compilation Target Java source file compiled directly to bytecode (.class). Translated first into a Java Servlet source file, and then compiled into bytecode.
Custom Tag Libraries Does not natively support custom XML tag libraries. Supports rich tag libraries (JSTL, custom tags) to eliminate raw Java code completely.
3. JSP Directives: page, include & taglib
⭐ CSJMU PYQs: 2025–26, 2023–24, 2020, 2017 (Explain JSP Directives; Static vs Dynamic Include)

Directives (<%@ directive attribute="value" %>) are messages sent to the JSP container that control how the entire JSP page is translated into a servlet. They do not produce direct output to the client.

Directive Syntax Example Purpose & Key Attributes
Page Directive <%@ page import="java.util.*" isErrorPage="false" %> Defines page-wide attributes: import, contentType, session, isErrorPage, errorPage, buffer.
Include Directive <%@ include file="header.jsp" %> Static Include: Merges the source code of the target file into the current page at translation time before compiling.
Taglib Directive <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> Declares a custom tag library or JSTL prefix to be used throughout the JSP page.
⚠️ Static Include (<%@ include %>) vs Dynamic Include (<jsp:include>):
• <%@ include file="navbar.jsp" %> (Static): Merges file text during translation phase. Only ONE servlet class is generated. If navbar.jsp is modified, the parent page may not reflect updates without manual re-translation.
• <jsp:include page="navbar.jsp" /> (Dynamic): Executes the target page at request time via RequestDispatcher.include(). TWO separate servlets are generated. Any changes to navbar.jsp appear instantly on the next refresh!
4. Scripting Elements & Generated Servlet Placement
⭐ CSJMU PYQs: 2024–25, 2022, 2019 (Explain Scriptlets, Expressions, and Declarations with code)

JSP offers three primary syntax mechanisms to embed Java logic into an HTML document:

Scripting Tag Syntax Where Placed in Generated Servlet Key Examination Rule
Declaration <%! int count = 0; %>
<%! public int add(int a, int b) { return a+b; } %>
Placed outside _jspService() directly in the servlet class body as instance variables and methods. Variables declared here are instance variables shared by all concurrent user requests (thread-safety risk!).
Scriptlet <% int x = 10; out.println(x); %> Placed inside the body of _jspService(). Variables declared here are local variables allocated on the thread stack per request (thread-safe).
Expression <%= new java.util.Date() %> Translated into an argument of out.print(...) inside _jspService(): out.print(new java.util.Date()); NEVER place a semicolon (;) at the end of an expression! Writing <%= x; %> produces invalid Java syntax out.print(x;); and crashes compilation!
5. The 9 Implicit Objects & The 4 Scopes
⭐ CSJMU PYQs: 2025–26, 2023–24, 2020 (Name and describe all 9 implicit objects & 4 scopes — Guaranteed 10 Marks!)
⚡ Essential Pass Content

The JSP container automatically declares and initializes Nine Pre-Defined Objects inside the _jspService() method body so developers can use them immediately in scriptlets and expressions without any explicit instantiation:

Implicit Object Underlying Java Type Native Scope Core Functionality
request javax.servlet.http.HttpServletRequest Request Reads HTTP request parameters (getParameter()), headers, cookies, and HTTP methods.
response javax.servlet.http.HttpServletResponse Page Configures response headers, MIME content types, cookies, and client redirection (sendRedirect()).
out javax.servlet.jsp.JspWriter Page Buffered character output stream used to write HTML markup to the client's browser.
session javax.servlet.http.HttpSession Session Stores user-specific session state across multiple HTTP requests (e.g. login credentials, shopping cart).
application javax.servlet.ServletContext Application Global shared context accessible by every user, servlet, and JSP across the entire web application.
config javax.servlet.ServletConfig Page Retrieves servlet/JSP initialization parameters defined in web.xml.
pageContext javax.servlet.jsp.PageContext Page Central context providing programmatic access to all 4 scopes, attributes, and other implicit objects.
page java.lang.Object (this) Page Synonym for the this keyword representing the current translated servlet instance.
exception java.lang.Throwable Page Only available in designated error pages (pages with <%@ page isErrorPage="true" %>).
The 4 Attribute Scopes in JSP:
  1. Page Scope (Default): Objects are accessible only within the current JSP page. Memory is freed as soon as the response is sent.
  2. Request Scope: Objects survive across server-side forward operations (RequestDispatcher.forward()) until the client request terminates.
  3. Session Scope: Objects persist across multiple requests from the same user browser until session timeout or logout (session.invalidate()).
  4. Application Scope: Objects live in server RAM from server boot to server shutdown, shared by all users worldwide.
6. JavaBeans in JSP (Standard Action Tags)
⭐ CSJMU PYQs: 2024–25, 2021, 2018 (Explain JavaBeans and jsp:useBean, jsp:setProperty, jsp:getProperty)

A JavaBean is a reusable software component written in Java. In the MVC architecture, JavaBeans represent the Model layer.

The 3 Essential Rules of a JavaBean Class:
  • Must implement java.io.Serializable.
  • Must provide a public no-argument constructor (default constructor).
  • All properties must be private, accessed strictly via public getters and setters (e.g. getName() and setName()).
StudentBean.java (Model Class)
package com.exam;
import java.io.Serializable;

public class StudentBean implements Serializable {
    private String name;
    private int marks;

    // 1. Mandatory public no-arg constructor
    public StudentBean() {}

    // 2. Getter and Setter methods
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int getMarks() { return marks; }
    public void setMarks(int marks) { this.marks = marks; }
}
JSP Action Tags: studentDisplay.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!-- Instantiate or locate existing JavaBean in session scope -->
<jsp:useBean id="student" class="com.exam.StudentBean" scope="session" />

<!-- Set bean properties automatically from HTTP request form parameters -->
<jsp:setProperty name="student" property="*" />

<!DOCTYPE html>
<html>
<head><title>Student Details</title></head>
<body>
    <h2>Student Profile</h2>
    <p>Student Name: <b><jsp:getProperty name="student" property="name" /></b></p>
    <p>Marks Scored: <b><jsp:getProperty name="student" property="marks" /></b></p>
</body>
</html>
7. Solved University Exam Program: Sum of Numbers 1 to 25
⭐ CSJMU PYQs: 2023–24, 2020 (Write a complete JSP page demonstrating Declarations, Scriptlets, and Expressions)
Complete JSP Program (sumCalculation.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>JSP Calculation Demo</title>
</head>
<body>
    <h2>Sum of Integers from 1 to 25</h2>

    <%! 
        // JSP Declaration: class-level helper method placed outside _jspService()
        int computeSum(int n) {
            return (n * (n + 1)) / 2; // Mathematical summation formula: n(n+1)/2
        }
    %>

    <%
        // JSP Scriptlet: procedural calculation inside _jspService() method body
        int total = computeSum(25);
    %>

    <p>The calculated sum of integers 1 to 25 is: <strong><%= total %></strong></p>
    <p>Server Execution Timestamp: <%= new java.util.Date() %></p>
</body>
</html>
8. Exam Answer Blueprint & Pitfalls to Avoid
How to Score Full 10 Marks on "JSP Lifecycle & Implicit Objects":
  1. Translation to Servlet (2 Marks): Explicitly explain that JSP is translated into a Servlet by the container on the first request. Draw the 5-box lifecycle flow.
  2. The 3 Lifecycle Methods (3 Marks): Write signatures for `jspInit()`, `_jspService()`, and `jspDestroy()`. State that `_jspService()` cannot be overridden.
  3. 9 Implicit Objects Table (4 Marks): Create a table listing all 9 objects with their underlying Java classes and scopes.
  4. Scripting Syntax (1 Mark): Write examples of `<%! %>`, `<% %>`, and `<%= %>`.
⚠️ Common Exam Pitfalls:
• Writing a semicolon inside an expression: Writing `<%= count; %>` causes an instant syntax error `out.print(count;);`! Never put semicolons in expressions!
• Confusing Static and Dynamic Include: Static include (`<%@ include %>`) merges code at translation time. Dynamic include (``) executes at request time via `RequestDispatcher`. Mixing them up loses 4 marks!
📝 Unit V Exam Mastery MCQ Quiz (10 Questions)

Answer all 10 questions covering JSP lifecycles, scripting elements, and the 9 implicit objects.