0% found this document useful (0 votes)
1 views20 pages

Java Servlet JSP Notes

The document provides comprehensive notes on Java Web Technologies, focusing on Java Servlets and JavaServer Pages (JSP). It covers key topics such as the servlet lifecycle, Tomcat configuration, handling HTTP requests, session tracking, and the differences between servlets and JSP. Additionally, it includes practical examples and solved questions to aid understanding of these technologies.

Uploaded by

sernibn8400
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views20 pages

Java Servlet JSP Notes

The document provides comprehensive notes on Java Web Technologies, focusing on Java Servlets and JavaServer Pages (JSP). It covers key topics such as the servlet lifecycle, Tomcat configuration, handling HTTP requests, session tracking, and the differences between servlets and JSP. Additionally, it includes practical examples and solved questions to aid understanding of these technologies.

Uploaded by

sernibn8400
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIVERSITY STUDY NOTES

Unit 4: Java Web Technologies


Java Servlets & JavaServer Pages (JSP)
Complete Lecture Notes with Examples & Solved Questions

Topics Covered: Servlets • Lifecycle • Tomcat • HTTP • Sessions • Cookies • JSP • Scripting • Directives
PART A: JAVA SERVLETS

1. Introduction to Servlets
A Java Servlet is a server-side Java program that handles HTTP requests and generates dynamic web
responses. Servlets run inside a Servlet Container (also called a web container) such as Apache
Tomcat and act as the middle layer between client requests and server-side business logic or
databases.

Why Are Servlets Used?


• Platform independence — runs on any OS with a JVM
• Better performance than CGI scripts (servlets stay in memory)
• Powerful — full access to all Java APIs (JDBC, file I/O, networking)
• Session management and state maintenance built-in
• Secure — Java's strong type-checking and exception handling
• Scalable — multithreading handles multiple requests simultaneously

Servlets vs. CGI


Feature Description
Feature Servlet vs CGI
Process model Single JVM process, multiple threads vs. new OS process per
request
Performance High (stays in memory) vs. Low (process creation overhead)
Platform Platform-independent (Java) vs. OS-dependent
Session Built-in session support vs. manual cookie management

2. Hierarchy of Servlets
Java Servlet API defines a clear class hierarchy for building servlets:
[Link] (Interface)
|
├── init(ServletConfig)
├── service(ServletRequest, ServletResponse)
└── destroy()

[Link] (Abstract Class)


| — protocol-independent servlet
|
[Link] (Abstract Class)
| — HTTP-specific servlet
|
├── doGet(HttpServletRequest, HttpServletResponse)
├── doPost(HttpServletRequest, HttpServletResponse)
├── doPut(...)
└── doDelete(...)

Servlet Interface: Defines three core life-cycle methods: init(), service(), destroy(). All servlets must
implement this interface directly or indirectly.
GenericServlet: An abstract class implementing Servlet and ServletConfig. It provides a protocol-
independent base class. You need to override service() method.
HttpServlet: Extends GenericServlet and provides HTTP-specific implementations. Its service()
method dispatches HTTP methods to doGet(), doPost(), etc. This is the class you typically extend in
real projects.

3. Life Cycle of a Servlet


The servlet lifecycle is managed by the servlet container (Tomcat). It consists of five distinct phases:

Servlet Lifecycle Phases


1. Loading → 2. Instantiation → 3. Initialization (init()) → 4. Request Handling (service()) →
5. Destruction (destroy())

Phase 1: Loading and Instantiation


The container loads the servlet class and creates one instance (using the no-arg constructor). This
happens when the server starts or on the first request.

Phase 2: Initialization — init()


Called once after instantiation. Used to perform one-time setup: opening database connections, reading
configuration, loading properties. Receives a ServletConfig object.
public void init(ServletConfig config) throws ServletException {
// One-time initialization
[Link](config);
[Link]("Servlet Initialized");
}

Phase 3: Request Handling — service()


Called for every client request. In HttpServlet, this method reads the HTTP method and delegates to
doGet(), doPost(), etc. This runs in a new thread per request.
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello from Servlet!</h1>");
}

Phase 4: Destruction — destroy()


Called once when the servlet is taken out of service (server shutdown or redeployment). Used to
release resources: closing DB connections, saving state.
public void destroy() {
[Link]("Servlet destroyed");
// Close database connections here
}

Key Point
init() and destroy() are called only ONCE in the servlet's lifetime. service() / doGet() / doPost()
are called for every request. The servlet container creates only ONE instance of each servlet
class and handles concurrent requests using threads.

4. Tomcat Configuration
Apache Tomcat is the most widely used servlet container. It implements the Java Servlet and JSP
specifications. Below is how to configure and deploy a servlet on Tomcat.

Project Directory Structure


MyWebApp/
├── WEB-INF/
│ ├── [Link] ← Deployment Descriptor
│ └── classes/
│ └── [Link]
└── [Link]

[Link] — Deployment Descriptor


The [Link] file maps URL patterns to servlet classes. It is placed inside WEB-INF/ folder.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="[Link] version="3.1">

<!-- Declare the servlet -->


<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<!-- Map URL pattern to servlet -->


<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>

Annotation-Based Configuration (Servlet 3.0+)


From Servlet 3.0 onwards, [Link] is optional. You can use the @WebServlet annotation:
import [Link];

@WebServlet("/hello") // Maps URL /hello to this servlet


public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link]().println("Hello World!");
}
}

5. Handling GET and POST Requests (HTTP)


HTTP defines several request methods. The two most common are GET and POST. HttpServlet
provides dedicated methods for each.

GET Request
Used to retrieve data. Parameters are appended to the URL (query string). GET requests are visible in
the browser address bar and can be bookmarked. Limited data size (~2KB).
// URL: [Link]

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

String name = [Link]("name"); // Read query param


[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Hello, " + name + "!</h2>");
[Link]("</body></html>");
}

POST Request
Used to submit data to the server (forms, login, file upload). Parameters are sent in the HTTP request
body — not visible in URL. Supports large amounts of data. More secure than GET for sensitive data.
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

String username = [Link]("username");


String password = [Link]("password");

[Link]("text/html");
PrintWriter out = [Link]();

if ("admin".equals(username) && "1234".equals(password)) {


[Link]("<h2>Login Successful!</h2>");
} else {
[Link]("<h2>Invalid Credentials</h2>");
}
}
Method Description
GET Data in URL, cacheable, bookmarkable, limited size (~2KB), less
secure
POST Data in body, not cached, not bookmarkable, unlimited size, more
secure
PUT Update an existing resource on the server
DELETE Delete a resource from the server

6. Handling Data from HTML to a Servlet


The most common use case is reading form data submitted by the user. The servlet reads form fields
using [Link]().

HTML Form ([Link])


<!DOCTYPE html>
<html>
<head><title>Student Registration</title></head>
<body>
<h2>Student Registration Form</h2>
<form action="register" method="post">
Name: <input type="text" name="sname"><br>
Roll No: <input type="number" name="roll" ><br>
Branch: <input type="text" name="branch"><br>
<input type="submit" value="Register">
</form>
</body>
</html>

Servlet ([Link])
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// Reading form data


String name = [Link]("sname");
String roll = [Link]("roll");
String branch = [Link]("branch");

// Set response type


[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Registration Successful!</h2>");
[Link]("<p>Name: " + name + "</p>");
[Link]("<p>Roll: " + roll + "</p>");
[Link]("<p>Branch: " + branch + "</p>");
[Link]("</body></html>");
}
}

Reading Multiple Values (Checkboxes, Multi-select)


// For checkboxes or multi-select inputs:
String[] hobbies = [Link]("hobby");
if (hobbies != null) {
for (String h : hobbies) {
[Link]("Hobby: " + h + "<br>");
}
}

7. Session Tracking
HTTP is a stateless protocol — each request is independent. The server does not remember previous
interactions. Session tracking is the mechanism to maintain state (user identity, cart items, preferences)
across multiple HTTP requests.

Session Tracking Mechanisms


• Cookies
• HttpSession (server-side sessions)
• URL Rewriting (appending session ID to URLs)
• Hidden Form Fields

7.1 Cookies
A Cookie is a small piece of text data stored on the client (browser) by the server. The browser sends
the cookie back with every subsequent request to the same server. Cookies are ideal for storing
lightweight, non-sensitive information like preferences or user IDs.

Creating and Sending a Cookie


// Create a cookie
Cookie userCookie = new Cookie("username", "Alice");
[Link](60 * 60 * 24); // Expires in 1 day (seconds)
[Link]("/"); // Available across entire app

// Send cookie to client


[Link](userCookie);

PrintWriter out = [Link]();


[Link]("Cookie set for user: Alice");
Reading a Cookie
Cookie[] cookies = [Link]();

if (cookies != null) {
for (Cookie c : cookies) {
if ([Link]().equals("username")) {
String user = [Link]();
[Link]("Welcome back, " + user + "!");
}
}
}

Deleting a Cookie
// Setting maxAge to 0 deletes the cookie
Cookie c = new Cookie("username", "");
[Link](0);
[Link](c);

Cookie Properties
Method Description
setMaxAge(sec) Cookie lifetime in seconds. 0 = delete. -1 = session cookie
setPath(path) Scope of cookie (e.g., "/" for entire app)
setDomain(d) Domain to which the cookie belongs
setSecure(b) If true, cookie sent only over HTTPS
setHttpOnly(b) If true, cookie not accessible by JavaScript (XSS protection)

7.2 HttpSession
HttpSession stores session data on the server side. A unique session ID is assigned to each client
(sent as a cookie or URL parameter). This is more secure than cookies as sensitive data stays on the
server.

Creating / Accessing a Session


// getSession(true) creates new session if one doesn't exist
HttpSession session = [Link](true);

// Store data in session


[Link]("loggedInUser", "Alice");
[Link]("cartCount", 3);

// Set session timeout (in seconds)


[Link](30 * 60); // 30 minutes

Reading Session Data


HttpSession session = [Link](false); // false = don't create if
absent

if (session != null) {
String user = (String) [Link]("loggedInUser");
[Link]("User: " + user);
} else {
[Link]("[Link]"); // Redirect to login
}

Invalidating a Session (Logout)


HttpSession session = [Link](false);
if (session != null) {
[Link](); // Destroys session and all its data
}
[Link]("[Link]");

Method Characteristics
Cookies Client-side storage, size limited (~4KB), not secure for sensitive
data
HttpSession Server-side storage, no size limit, secure, identified by session ID
URL Rewriting Session ID appended to URL, used when cookies are disabled

Practice Questions — Servlets

Q1. What is a Servlet? Explain the Servlet Lifecycle with a diagram.

Answer:
A Servlet is a Java class running on the server that handles HTTP requests and produces HTTP
responses.
Lifecycle: 1) Loading — container loads servlet class. 2) Instantiation — single object created. 3)
init() — called once for setup. 4) service()/doGet()/doPost() — called per request in a thread. 5)
destroy() — called once on shutdown to free resources.
Key: init() and destroy() run once. service() runs per request. Only ONE servlet instance exists
regardless of concurrent users.

Q2. Differentiate between doGet() and doPost() methods.

Answer:
doGet(): Handles HTTP GET requests. Data sent as query string in URL. Visible to users,
bookmarkable. Limited to ~2KB. Idempotent — repeated calls give same result. Used for
fetching/displaying data.
doPost(): Handles HTTP POST requests. Data sent in request body. Not visible in URL.
Supports unlimited data. Not idempotent. Used for form submissions, logins, file uploads.
Both are overridden in HttpServlet. They take HttpServletRequest and HttpServletResponse as
parameters.

Q3. Write a servlet to accept student name and roll number from an HTML form and
display the details.

Answer:
HTML Form ([Link]): Create a <form action='StudentServlet' method='post'> with input fields
name='sname' and name='roll', and a submit button.
Servlet ([Link]): Annotate with @WebServlet('/StudentServlet'). In doPost(), use
[Link]('sname') and [Link]('roll') to read values. Use
[Link]() to print the HTML response with those values.

Q4. Explain session tracking using Cookies with an example.

Answer:
Session tracking maintains user state across stateless HTTP requests. Cookies store small text
data on the client browser.
To set: new Cookie('name', 'value'), setMaxAge(seconds), [Link](cookie).
To read: [Link]() returns Cookie[], loop through and use getName()/getValue().
Use case: Remember a logged-in username so the user doesn't have to log in on every page.
Limitation: Limited to 4KB, not suitable for sensitive data — use HttpSession instead.

Q5. Compare Cookies and HttpSession for session tracking.

Answer:
Cookies: Data stored on client. Maximum ~4KB. Visible to client, can be tampered. Persists
across browser restarts if maxAge > 0. Not suitable for sensitive data.
HttpSession: Data stored on server. No practical size limit. Client only holds session ID.
Destroyed when browser closes (by default) or when invalidate() is called. Secure for sensitive
data like logged-in user details, cart.
PART B: JAVASERVER PAGES (JSP)

8. Introduction to JavaServer Pages (JSP)


JavaServer Pages (JSP) is a server-side technology that allows embedding Java code directly inside
HTML pages. JSP simplifies the creation of dynamic web content. Internally, JSP pages are
automatically converted into Servlets by the JSP engine (Tomcat's Jasper compiler).

Why JSP Instead of Servlets Alone?


• In Servlets, writing HTML inside Java code (PrintWriter) is cumbersome and hard to maintain.
• JSP separates presentation (HTML) from business logic (Java).
• JSP is ideal for the View layer in MVC architecture.
• Web designers can work on JSP files without knowing Java deeply.
• JSP has built-in implicit objects (request, response, session, etc.) automatically available.

9. Simple JSP Program


A JSP file has a .jsp extension. Below is a Hello World JSP example:
<!-- [Link] -->
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>My First JSP</title>
</head>
<body>
<h1>Hello from JSP!</h1>
<%
// Java code (Scriptlet)
String msg = "Welcome to Java Web Development";
[Link]("<p>" + msg + "</p>");
%>
<p>Current time: <%= new [Link]() %></p>
</body>
</html>

When a user requests [Link], Tomcat converts it to a Servlet class, compiles it, and sends the HTML
output to the browser.

10. Life Cycle of a JSP


The JSP lifecycle is managed by the JSP container (Tomcat's Jasper). It has 7 phases:

JSP Lifecycle Phases


1. Translation → 2. Compilation → 3. Loading → 4. Instantiation → 5. jspInit() → 6.
_jspService() → 7. jspDestroy()
1. Translation: The JSP file is converted to a Java Servlet source file (.java) by Jasper.
2. Compilation: The .java file is compiled to a .class file.
3. Loading: The .class file is loaded into the JVM.
4. Instantiation: An object of the generated servlet class is created.
5. jspInit(): Called once, like servlet's init(). Used for one-time setup. Can be overridden.
6. _jspService(): Called for every client request. Handles all HTTP methods. Cannot be overridden
(auto-generated).
7. jspDestroy(): Called once when JSP is taken out of service. Used to release resources.

// Overriding jspInit() and jspDestroy() in JSP:


<%!
public void jspInit() {
[Link]("JSP Initialized");
}
public void jspDestroy() {
[Link]("JSP Destroyed");
}
%>

Important Note
The JSP is only translated and compiled on the FIRST request (or if modified). Subsequent
requests use the compiled class directly, making JSP as fast as a Servlet.

11. Implicit Objects in JSP


JSP provides 9 implicit objects that are automatically available in the _jspService() method. You can
use them without declaring or initializing them.

Object Type & Purpose


request HttpServletRequest — access request params, headers, attributes
response HttpServletResponse — set response type, headers, cookies
out JspWriter — write output to HTML response (like PrintWriter)
session HttpSession — store/retrieve session-scoped data
application ServletContext — app-wide shared data and initialization params
config ServletConfig — servlet configuration parameters
pageContext PageContext — access all other implicit objects, page-level
attributes
page Object — refers to current JSP page instance (this)
exception Throwable — only in error pages (isErrorPage=true)

Example: Using Implicit Objects


<!-- [Link] -->
<%@ page language="java" %>
<html><body>

<!-- 'request' implicit object -->


<p>Client IP: <%= [Link]() %></p>

<!-- 'session' implicit object -->


<%
[Link]("user", "Alice");
String user = (String) [Link]("user");
%>
<p>Logged in as: <%= user %></p>

<!-- 'application' implicit object -->


<%
[Link]("visits",
((Integer) [Link]("visits") == null ? 1 :
(Integer) [Link]("visits") + 1));
%>
<p>Total visits: <%= [Link]("visits") %></p>

</body></html>

12. Scripting Elements


JSP scripting elements allow Java code to be embedded directly in JSP pages. There are four types:

12.1 Declarations <%! ... %>


Used to declare variables and methods at the class level (outside _jspService()). Variables declared
here are instance variables shared across requests. Methods defined here can be called from the page.
<%!
// Class-level variable (shared across all requests)
int visitCount = 0;

// Class-level method
String greet(String name) {
return "Hello, " + name + "!";
}
%>

<% visitCount++; %>


<p>Page visits: <%= visitCount %></p>
<p><%= greet("Alice") %></p>

Warning
Variables declared with <%! %> are instance variables of the servlet. Since a single servlet
instance serves multiple requests concurrently, these variables are NOT thread-safe. Prefer
local variables inside <% %> scriptlets for request-specific data.

12.2 Expressions <%= ... %>


Used to output the value of a Java expression directly into the HTML. The expression is evaluated,
converted to a String, and inserted at that position. No semicolon is used inside the expression tag.
<!-- Expression syntax -->
<p>Today is: <%= new [Link]() %></p>
<p>2 + 3 = <%= 2 + 3 %></p>
<p>Hello, <%= [Link]("name") %>!</p>

<!-- Equivalent servlet code (handled automatically): -->


<!-- [Link](new [Link]()); -->

12.3 Scriptlets <% ... %>


A scriptlet contains any valid Java code. This code is placed inside the _jspService() method. Multiple
scriptlets on a page are treated as if they are consecutive Java statements. HTML between scriptlets is
output literally.
<%
int n = [Link]([Link]("n"));
if (n % 2 == 0) {
%>
<p><%= n %> is EVEN</p>
<%
} else {
%>
<p><%= n %> is ODD</p>
<%
}
%>

<!-- Loop example -->


<ul>
<% for (int i = 1; i <= 5; i++) { %>
<li>Item <%= i %></li>
<% } %>
</ul>

12.4 Comments
JSP supports two types of comments:
Type Syntax & Behavior
JSP Comment <%-- This is a JSP comment --%> — Not sent to client, not visible
in page source
HTML Comment <!-- This is HTML --> — Sent to client, visible in page source via
View Source
Java Comment // or /* */ inside scriptlets — Not sent to client

<%-- This JSP comment is NEVER sent to the browser --%>


<!-- This HTML comment IS sent to the browser -->
<%
// This Java comment is inside scriptlet, not sent to browser
int x = 10; /* block comment */
%>
13. JSP Directives
JSP directives provide global information about the entire JSP page to the container. They are
processed at translation time (not at request time). Directive syntax: <%@ directive attribute="value"
%>

13.1 Page Directive <%@ page ... %>


The most important directive. Defines page-level properties such as import statements, content type,
error page, session management, buffering, and more.
<%@ page language="java"
contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"
import="[Link].*, [Link].*"
session="true"
buffer="8kb"
errorPage="[Link]"
isErrorPage="false"
%>

Attribute Purpose
language Scripting language used (default: java)
contentType MIME type of response (default: text/html)
import Java packages/classes to import (like Java's import statement)
session true/false — whether page participates in session (default: true)
buffer Output buffer size (default: 8kb). 'none' for no buffering
errorPage URL of the error page to redirect to on exception
isErrorPage true = this page is an error page; exception object is available
pageEncoding Character encoding of the JSP source file

Error Page Example


<!-- [Link] -->
<%@ page errorPage="[Link]" %>
<%
int result = 10 / 0; // This throws ArithmeticException
%>

<!-- [Link] -->


<%@ page isErrorPage="true" %>
<html><body>
<h2>Oops! An error occurred:</h2>
<p><%= [Link]() %></p>
</body></html>

13.2 Include Directive <%@ include ... %>


Statically includes the content of another file at translation time. The included file becomes part of the
current JSP before compilation. Used for common page elements like headers, footers, navigation
bars.
<!-- Including a common header at translation time -->
<%@ include file="[Link]" %>

<h2>Main Page Content Here</h2>


<p>Welcome to the university portal.</p>

<%@ include file="[Link]" %>

<!-- [Link] -->


<html><body>
<div style='background:#1A3A5C; color:white; padding:10px'>
<h1>University Management System</h1>
</div>

<!-- [Link] -->


<div style='text-align:center; color:gray; margin-top:20px'>
© 2024 University. All Rights Reserved.
</div>
</body></html>

Static vs Dynamic Include


<%@ include file='[Link]' %> — STATIC. Included at translation time. One compiled class.
Variables/methods shared between files.
<jsp:include page='[Link]' /> — DYNAMIC. Included at request time. Separate compiled class.
Output is merged. Use when included content changes frequently.

13.3 Taglib Directive <%@ taglib ... %>


Declares a custom tag library (like JSTL) for use in the JSP page. Although JSTL is a separate topic,
knowing the taglib directive is important.
<%@ taglib uri="[Link] prefix="c" %>
<c:out value="${name}" />
<c:forEach var="item" items="${list}">
<p>${item}</p>
</c:forEach>

14. Mixing Scriptlets and HTML


JSP allows seamless mixing of Java code and HTML. The key is that Java control structures (if, for,
while) can span multiple scriptlets with HTML in between.

Example: Dynamic Table using Loop


<%@ page import="[Link].*" %>
<%
String[] students = {"Alice", "Bob", "Carol", "David", "Eve"};
int[] marks = {85, 72, 91, 63, 78};
%>
<html>
<head><title>Student Marks</title></head>
<body>
<h2>Student Result Table</h2>
<table border='1'>
<tr><th>No.</th><th>Name</th><th>Marks</th><th>Grade</th></tr>
<% for (int i = 0; i < [Link]; i++) { %>
<tr>
<td><%= i+1 %></td>
<td><%= students[i] %></td>
<td><%= marks[i] %></td>
<td>
<% if (marks[i] >= 90) { %>
<span style='color:green'>A</span>
<% } else if (marks[i] >= 75) { %>
<span style='color:blue'>B</span>
<% } else { %>
<span style='color:red'>C</span>
<% } %>
</td>
</tr>
<% } %>
</table>
</body>
</html>

Example: Reading Form Data in JSP


<!-- [Link] -->
<form action='[Link]' method='get'>
Enter your name: <input type='text' name='uname'>
<input type='submit' value='Greet'>
</form>

<!-- [Link] -->


<%@ page language='java' %>
<html><body>
<%
String name = [Link]("uname");
if (name == null || [Link]()) {
name = "Guest";
}
%>
<h2>Hello, <%= name %>! Welcome to our site.</h2>
<p>Your name has <%= [Link]() %> characters.</p>
</body></html>

Practice Questions — JSP

Q6. What is JSP? How is it different from a Servlet?

Answer:
JSP (JavaServer Pages) is a server-side technology for creating dynamic web content by
embedding Java code in HTML. It is automatically translated into a Servlet by the container
(Jasper in Tomcat).
Difference: In Servlets, HTML is written in Java using PrintWriter — messy and hard to maintain.
In JSP, HTML is the primary structure with Java embedded inside — cleaner separation of UI
and logic. JSP is better for presentation; Servlets are better for complex processing. MVC
architecture uses Servlets as Controller and JSP as View.

Q7. Explain the JSP Life Cycle in detail.

Answer:
Phase 1 — Translation: Jasper converts the .jsp file to a .java Servlet source file. HTML
becomes [Link]() calls; scriptlets become inline code.
Phase 2 — Compilation: The .java file is compiled to a .class file.
Phase 3-4 — Loading & Instantiation: JVM loads the class and creates one instance.
Phase 5 — jspInit(): Called once. Override for one-time resource setup (like init() in Servlet).
Phase 6 — _jspService(): Called for each request. Cannot be overridden. Contains translated
page logic.
Phase 7 — jspDestroy(): Called once when JSP is destroyed. Override to release resources.

Q8. List and explain JSP Implicit Objects with examples.

Answer:
1. request — HttpServletRequest. Access form data: [Link]('name').
2. response — HttpServletResponse. Set headers: [Link]('text/html').
3. out — JspWriter. Print to browser: [Link]('Hello').
4. session — HttpSession. Store user data: [Link]('user', 'Alice').
5. application — ServletContext. App-wide data: [Link]('hits', count).
6. config — ServletConfig. Init params: [Link]('param').
7. pageContext — PageContext. Access all scopes and other implicit objects.
8. page — this reference to current servlet instance.
9. exception — Throwable. Only in error pages. [Link]().

Q9. Explain JSP Scripting Elements: Declarations, Expressions, Scriptlets, and


Comments.

Answer:
Declaration (<%! %>): Declares class-level variables and methods. Code placed outside
_jspService(). Example: <%! int count = 0; String greet(){ return 'Hi'; } %>
Expression (<%= %>): Outputs value of a Java expression. No semicolon. Auto-converts to
String. Example: <%= new Date() %>
Scriptlet (<% %>): Any valid Java code inside _jspService(). Can mix with HTML using
interleaved tags. Example: <% if(x>0){ %> Positive <% } %>
Comment (<%-- --%>): JSP comment never sent to client. HTML comment <!-- --> is sent. Java
comment // inside scriptlets is not sent.

Q10. Explain JSP Page Directive and Include Directive with examples.
Answer:
Page Directive (<%@ page %>): Sets page-level properties at translation time. Key attributes:
import (imports Java packages), contentType (response MIME type), session (enable/disable),
errorPage (redirect on exception), isErrorPage (marks error page enabling 'exception' object).
Example: <%@ page import='[Link].*' contentType='text/html' session='true'
errorPage='[Link]' %>
Include Directive (<%@ include file='...' %>): Statically includes another file at translation time.
The included content becomes part of the same compiled class. Used for reusable headers,
footers, navigation.
Example: <%@ include file='[Link]' %> at the top and <%@ include file='[Link]' %> at
the bottom.
Unlike <jsp:include>, the static include shares scope with the main page — variables defined in
the included file are accessible in the main page.

Q11. Write a JSP program to display a multiplication table for a number entered by
the user.

Answer:
HTML Form: <form action='[Link]' method='get'><input type='number' name='n'><input
type='submit' value='Generate'></form>
[Link]: <%@ page language='java' %><html><body><% int n =
[Link]([Link]('n')); %><h2>Table of <%= n %></h2><table
border='1'><% for(int i=1; i<=10; i++){ %><tr><td><%= n %> × <%= i %></td><td><%= n*i
%></td></tr><% } %></table></body></html>
This demonstrates: page directive, request implicit object, scriptlet for loop, and expression tags
mixing seamlessly with HTML.

Q12. What is the difference between static include (<%@ include %>) and dynamic
include (<jsp:include />)?

Answer:
Static Include (<%@ include file='[Link]' %>): Included at TRANSLATION time. Both files
compiled into ONE class. Variables/methods are shared. Changes in included file require
recompilation of including file. Faster at runtime since there's only one class.
Dynamic Include (<jsp:include page='[Link]' />): Included at REQUEST time. Both files compiled
SEPARATELY. Output is merged at runtime. Changes in included file take effect without
recompiling main file. Slightly slower but more flexible. Can pass parameters using <jsp:param>.

Quick Revision Summary

Term Meaning
Servlet Server-side Java class handling HTTP req/res
GenericServlet Protocol-independent base, override service()
HttpServlet HTTP-specific, override doGet() / doPost()
Term Meaning
init() Called once at startup — setup resources
service() Called per request — dispatches to doGet/Post
destroy() Called once on shutdown — release resources
[Link] Deployment descriptor mapping URLs to servlets
@WebServlet Annotation alternative to [Link] mapping
Cookie Client-side, 4KB limit, name-value pair
HttpSession Server-side session, no size limit
JSP HTML with embedded Java, translated to Servlet
jspInit() JSP initialization, called once
_jspService() Core JSP method, called per request, auto-generated
<%! %> Declaration — class-level variables/methods
<%= %> Expression — outputs value, no semicolon
<% %> Scriptlet — any Java code
<%-- --%> JSP comment — not sent to browser
<%@ page %> Page directive — imports, contentType, error page
<%@ include %> Static include at translation time

— End of Unit 4 Notes —

You might also like