- Understand how the Web Container translates and compiles a
.jsppage into a Java Servlet. - Trace the three core lifecycle hooks:
jspInit(),_jspService(),jspDestroy(). - Contrast runtime request handling with compilation-time translation.
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!
The Lifecycle Methods in Detail:
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.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!public void jspDestroy(): Invoked by the container strictly once when the application is undeployed or the server shuts down, allowing cleanup of persistent resources.
| 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. |
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. |
<%@ 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!
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! |
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" %>). |
- Page Scope (Default): Objects are accessible only within the current JSP page. Memory is freed as soon as the response is sent.
- Request Scope: Objects survive across server-side forward operations (
RequestDispatcher.forward()) until the client request terminates. - Session Scope: Objects persist across multiple requests from the same user browser until session timeout or logout (
session.invalidate()). - Application Scope: Objects live in server RAM from server boot to server shutdown, shared by all users worldwide.
A JavaBean is a reusable software component written in Java. In the MVC architecture, JavaBeans represent the Model layer.
- 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()andsetName()).
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; }
}
<%@ 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>
<%@ 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>
- 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.
- The 3 Lifecycle Methods (3 Marks): Write signatures for `jspInit()`, `_jspService()`, and `jspDestroy()`. State that `_jspService()` cannot be overridden.
- 9 Implicit Objects Table (4 Marks): Create a table listing all 9 objects with their underlying Java classes and scopes.
- Scripting Syntax (1 Mark): Write examples of `<%! %>`, `<% %>`, and `<%= %>`.
• 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 (`
Answer all 10 questions covering JSP lifecycles, scripting elements, and the 9 implicit objects.