Java Servlet JSP Notes
Java Servlet JSP Notes
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.
2. Hierarchy of Servlets
Java Servlet API defines a clear class hierarchy for building servlets:
[Link] (Interface)
|
├── init(ServletConfig)
├── service(ServletRequest, ServletResponse)
└── destroy()
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.
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.
</web-app>
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]
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 {
[Link]("text/html");
PrintWriter out = [Link]();
Servlet ([Link])
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
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.
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.
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.
if (session != null) {
String user = (String) [Link]("loggedInUser");
[Link]("User: " + user);
} else {
[Link]("[Link]"); // Redirect to login
}
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
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.
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.
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.
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)
When a user requests [Link], Tomcat converts it to a Servlet class, compiles it, and sends the HTML
output to the browser.
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.
</body></html>
// Class-level method
String greet(String name) {
return "Hello, " + name + "!";
}
%>
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.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
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
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.
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.
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]().
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>.
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