0% found this document useful (0 votes)
27 views21 pages

Overview of Java Servlets

A Servlet is a Java class that processes requests and responses in web applications, acting as a bridge between clients and server-side resources. The document outlines the lifecycle of a Servlet, including loading, initialization, request handling, and destruction, as well as providing examples of basic servlet code and configuration using web.xml. It also discusses the Servlet API, deployment on Apache Tomcat, and the structure of a typical servlet project.

Uploaded by

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

Overview of Java Servlets

A Servlet is a Java class that processes requests and responses in web applications, acting as a bridge between clients and server-side resources. The document outlines the lifecycle of a Servlet, including loading, initialization, request handling, and destruction, as well as providing examples of basic servlet code and configuration using web.xml. It also discusses the Servlet API, deployment on Apache Tomcat, and the structure of a typical servlet project.

Uploaded by

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

Servlet Introduction

Introduction to Servlets

A Servlet is a Java class used to handle requests and responses in a web application. It runs on
a server and acts as a middle layer between a client (like a web browser) and a database or
application on the server.

Why Use Servlets?

 To generate dynamic web content (HTML, JSON, etc.)


 To process client requests (like form submissions)
 To connect Java code with HTML
 To manage sessions and cookies
 To handle tasks like authentication, data processing, and more

How Servlets Work – Life Cycle

1. Loading and Instantiation


The servlet is loaded and instantiated by the servlet container (like Apache Tomcat).
2. Initialization
The init() method is called once when the servlet is first created.
3. Request Handling
Each request calls the service() method, which may call:
o doGet() – for HTTP GET requests
o doPost() – for HTTP POST requests
4. Destruction
When the servlet is removed, the destroy() method is called to clean up resources.

Basic Servlet Code Example


import [Link].*;
import [Link].*;
import [Link].*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello, Servlet!</h1>");
}
}
Where Servlets Run

Servlets run in a Servlet Container like:

 Apache Tomcat
 Jetty
 GlassFish

Java Servlets Architecture


Java servlets container play a very important role. It is responsible for handling important tasks
like load balancing, session management and resource allocation, it make sure that all the
requests are process efficiently under high traffic. The container distribute requests accross
multiple instances, which helps improve the system performance.

Servlet Architecture can be depicted from the image itself as provided below as follows:

Servlet API Overview: [Link] & [Link]

The Servlet API is a set of Java interfaces and classes used to write servlets — server-side
programs that handle HTTP requests and generate responses.

There are two main packages:

1. [Link] Package

This package provides the core interfaces and classes for all types of servlets (generic or
HTTP-specific).
✨Key Interfaces and Classes:
Type Name Description

Interface Servlet The basic interface all servlets implement.

Simplified base class for creating protocol‐


Class GenericServlet
independent servlets.

Interface ServletConfig Provides servlet configuration (init params).

Provides web application context (shared


Interface ServletContext
resources, attributes).

For forwarding or including content from another


Interface RequestDispatcher
resource.

Represents a client request (protocol‐


Interface ServletRequest
independent).

Interface ServletResponse Represents the response to a client.

Used for request filtering (e.g., logging,


Interface Filter, FilterChain, FilterConfig
authentication).

ServletInputStream,
Interface For binary input/output.
ServletOutputStream

Example Use (GenericServlet):


public class MyServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
PrintWriter out = [Link]();
[Link]("Hello from GenericServlet!");
}
}

2. [Link] Package

This package builds on [Link] and provides HTTP-specific classes and interfaces.

Key Interfaces and Classes:


Type Name Description

Abstract class to simplify HTTP


Class HttpServlet
servlet creation.

Interface HttpServletRequest Represents an HTTP request.

Interface HttpServletResponse Represents an HTTP response.


Type Name Description

For session tracking between client


Interface HttpSession
and server.

Class Cookie Represents an HTTP cookie.

HttpSessionListener,
Interface For session lifecycle monitoring.
HttpSessionAttributeListener

HttpServlet Key Methods:


Method Use

doGet(HttpServletRequest req,
Handles GET requests.
HttpServletResponse res)

doPost(...) Handles POST requests.

doPut(...) / doDelete(...) For PUT and DELETE methods.

Retrieves request parameter (from form,


getParameter(String name)
query string).

setContentType(String type) Sets the MIME type of the response.

Example Use (HttpServlet):


public class HelloHttpServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello from HttpServlet!</h1>");
}
}

Servlet API Jar

If you're building a servlet app, you need the Servlet API JAR (like [Link]).
This is usually provided by the servlet container (e.g., Tomcat), but you may need to include it in
your development environment.

Maven Dependency Example:

<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
Servlet Life Cycle in Java

The Servlet Life Cycle defines the stages a servlet goes through during its existence — from
loading to destruction — managed by the Servlet container (e.g., Apache Tomcat).

4 Main Phases of Servlet Life Cycle

Phase Method Description

1. Loading & Servlet class is loaded and an


Constructor
Instantiation object is created.

Called once when the servlet is


2. Initialization init(ServletConfig config)
initialized.

3. Request service(ServletRequest req,


Called for each client request.
Handling ServletResponse res)

Called once when servlet is being


4. Destruction destroy()
taken out of service.

Lifecycle Flow
1. Client makes HTTP request

2. Servlet container loads servlet class

3. Instantiates servlet object using no-arg constructor

4. Calls init() method (only once)

5. For each request, calls service() method
↳ which internally calls doGet(), doPost(), etc.

6. When shutting down or unloading, destroy() is called

Code Example
public class MyServlet extends HttpServlet {

@Override
public void init() throws ServletException {
[Link]("Servlet initialized");
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello from doGet()</h1>");
}
@Override
public void destroy() {
[Link]("Servlet destroyed");
}
}

Lifecycle Methods Explained

✅ init(ServletConfig config)

 Called once after the servlet is instantiated.


 Used for initialization tasks (e.g. database connection).
 ServletConfig provides servlet init parameters.

service(ServletRequest req, ServletResponse res)

 Called for every request.


 In HttpServlet, it delegates to:
o doGet() for GET requests
o doPost() for POST requests, etc.

❌destroy()

 Called when:
o The servlet is being unloaded
o The server is shutting down
 Use it to release resources (close DB, files, etc.).

Servlet Life Cycle Diagram


+----------------+
| Servlet Class |
+----------------+
|
v
[Loading & Instantiation]
|
v
init() — called once
|
v
+-----------------------------+
| service() — per request |
| → doGet(), doPost(), etc |
+-----------------------------+
|
v
destroy() — called once
Notes

 Servlet instance is singleton — only one per servlet class (unless explicitly configured
otherwise).
 service() is multi-threaded — separate thread for each request.
 Proper synchronization is necessary for shared resources.

What is [Link]?

 Located in: WEB-INF/[Link]


 It’s an XML file used to declare:
o Servlets
o Servlet mappings (URL patterns)
o Initialization parameters
o Load-on-startup behavior
o Filters, listeners, welcome pages, error pages, etc.

Basic [Link] Structure


<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
app_4_0.xsd"
version="4.0">

<!-- Servlet Declaration -->


<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<!-- Servlet Mapping -->


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

</web-app>

Example Servlet Class


package [Link];

import [Link].*;
import [Link].*;
import [Link].*;

public class HelloServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello from HelloServlet</h1>");
}
}

Explanation of Elements

Tag Description

<servlet> Declares the servlet class with a logical name.

<servlet-name> A unique name used to refer to the servlet.

<servlet-class> Fully qualified name of the servlet class.

<servlet-mapping> Maps the servlet to a specific URL pattern.

<url-pattern> The URL the client uses to access the servlet (e.g., /hello).

Optional Configuration Tags

✅ Initialization Parameters
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
<init-param>
<param-name>adminEmail</param-name>
<param-value>admin@[Link]</param-value>
</init-param>
</servlet>

✅ Load on Startup
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

 A non-negative number means the servlet loads when the app starts.
 Useful for initializing DB connections, caches, etc.

[Link] vs Annotations (Servlet 3.0+)

Feature [Link] @WebServlet Annotation

Servlet declaration Manual XML entry In code with annotations

Portability More portable Less portable (hardcoded class names)

Modernity Legacy / traditional Preferred in modern apps


✅Example with @WebServlet (No [Link] needed)

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
// same as before
}

You can still use both together — annotations override [Link] if conflicts occur.

Would you like help writing a full servlet project structure with [Link], or explanation of how
to deploy it on Tomcat?

You said:
yes

ChatGPT said:

Great! Here's a complete guide to writing a Servlet project using [Link] and deploying it on
Apache Tomcat.

✅1. Project Structure (Standard Java Web App)


MyWebApp/
├── WEB-INF/
│ ├── [Link]
│ └── classes/
│ └── com/
│ └── example/
│ └── [Link]
└── [Link]

2. Servlet Java Code

File: [Link]

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;

public class HelloServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello from HelloServlet</h1>");
}
}
➡ Compile it and place the .class file inside:

MyWebApp/WEB-INF/classes/com/example/[Link]

3. Deployment Descriptor — [Link]

File: MyWebApp/WEB-INF/[Link]

<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
app_4_0.xsd"
version="4.0">

<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

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

</web-app>

4. Optional: Static HTML File

File: MyWebApp/[Link]

<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>Welcome to My Web App</h2>
<a href="hello">Go to HelloServlet</a>
</body>
</html>

5. Deploy to Tomcat

Steps:

1. Install Apache Tomcat


o Download from: [Link]
o Extract to a known location (e.g., C:\Tomcat9)
2. Package your Web App
o Name the folder MyWebApp (as above)
o Optionally, zip it into a .war file:
o jar -cvf [Link] *
3. Copy to Tomcat
o Copy MyWebApp/ (or [Link]) to:
o C:\Tomcat9\webapps\
4. Start Tomcat
o Go to bin/ directory and run:
 On Windows: [Link]
 On Linux/macOS: ./[Link]
5. Access the App
o Open browser:
o [Link]
o Then go to the servlet:
o [Link]

Result

You should see:

<h1>Hello from HelloServlet</h1>

✅Successfully deployed a servlet using [Link]!

Developing and Deploying Servlets

Developing and Deploying Servlets – Complete Guide

Servlet development and deployment involve writing Java code, configuring it, compiling it, and
deploying it to a servlet container like Apache Tomcat.

✅ 1. Prerequisites

Before you begin:

 ✅Java JDK installed


 ✅Apache Tomcat (or any servlet container)
 ✅A text editor or IDE (like VS Code, IntelliJ, or Eclipse)
 ✅Basic knowledge of Java

2. Steps to Develop a Servlet

Project Folder Structure (Manual Setup)


MyServletApp/
├── WEB-INF/
│ ├── [Link]
│ └── classes/
│ └── com/
│ └── example/
│ └── [Link]
└── [Link] (optional)
A. Write the Servlet Class

File: [Link]

package [Link];

import [Link].*;
import [Link].*;
import [Link].*;

public class HelloServlet extends HttpServlet {


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Hello from HelloServlet</h2>");
}
}

B. Create Deployment Descriptor

File: WEB-INF/[Link]

<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
app_4_0.xsd"
version="4.0">

<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

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

</web-app>

C. Compile the Servlet

1. Set your classpath to include the servlet API JAR from Tomcat:

Windows:

set CLASSPATH=%CLASSPATH%;C:\Tomcat9\lib\[Link];
Linux/macOS:

export CLASSPATH=$CLASSPATH:/opt/tomcat/lib/[Link]

2. Compile the Java file:

javac -d WEB-INF/classes [Link]

3. Package as WAR (Optional but recommended)

Create a .war file (Web Application Archive):

jar -cvf [Link] *

4. Deploy to Apache Tomcat

Option 1: Copy Folder

 Copy the whole MyServletApp/ folder to:


 C:\Tomcat9\webapps\

Option 2: Deploy WAR File

 Copy [Link] to:


 C:\Tomcat9\webapps\

Tomcat will automatically extract and deploy the WAR.

▶ 5. Start Tomcat

Go to bin/ directory:

 On Windows:
Run [Link]
 On Linux/macOS:
Run ./[Link]

6. Access Your Servlet

Open your browser and go to:


[Link]

You should see:


Hello from HelloServlet

Handling Servlet Requests and Responses in Java


In Java Servlets, the two core objects for communication between the client (browser) and the
server (servlet) are:

 HttpServletRequest – represents the incoming client request


 HttpServletResponse – represents the outgoing response sent back to the client

Servlet Request‐Response Flow


Browser (Client)
|
|-------> [HttpServletRequest]
| (URL, headers, params, etc.)
|
|-------> Servlet (process logic)
|
|<------- [HttpServletResponse]
(HTML, JSON, files, etc.)

1. Handling Requests with HttpServletRequest


The request object lets you extract all data sent from the client, such as:

Common Methods:

Method Purpose

getParameter(String name) Get form/query parameter

getParameterValues(String name) Get multiple values (e.g. checkboxes)

getHeader(String name) Get header value

getMethod() Returns HTTP method (GET, POST, etc.)

getRequestURI() URI requested by the client

getSession() Returns the user's session

getCookies() Access cookies from client

getInputStream() Raw input (useful for JSON or binary data)

Example: Reading Form Data


String username = [Link]("username");
String password = [Link]("password");
If the user sends:

[Link]

→ username = "admin", password = "123"


2. Sending Responses with HttpServletResponse

The response object allows your servlet to send output back to the client.

Common Methods:

Method Purpose

Set MIME type (e.g., "text/html",


setContentType(String type)
"application/json")

getWriter() Returns PrintWriter for character data

getOutputStream() For binary data (e.g., images, PDFs)

sendRedirect(String location) Redirects to another URL

setStatus(int sc) Set HTTP status code (e.g. 200, 404)

addHeader(String name, String


Add custom response headers
value)

setCookie(Cookie cookie) Send cookies

Example: Sending HTML Response


[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Welcome, user!</h1>");

3. Complete Example – Handling Request and Response


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

// Get request data


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

// Set response type and write output


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

[Link]("<html><body>");
[Link]("<h2>Welcome, " + username + "</h2>");
[Link]("</body></html>");
}
Common Content Types in setContentType()
MIME Type Use

text/html Web pages

application/json JSON APIs

text/plain Plain text

application/pdf PDF files

image/jpeg JPEG image

Bonus: Difference Between doGet() and doPost()


Aspect doGet() doPost()

URL
Request
Data sent in (query
body
string)

Submitting
Reading
Use for data
data
(forms)

Limited
Larger
Size limit by URL
payloads
length

Visible in URL Yes No

Reading Initialization Parameters in Servlets

Initialization parameters are key-value pairs that can be defined in a


servlet’s configuration. They are typically used to store configuration
settings like database URLs, admin email, etc.

You can define them in two ways:

1. Using the deployment descriptor ([Link])


2. Using annotations (@WebInitParam)

✅1. Reading Init Parameters from [Link]


Aspect doGet() doPost()

Step 1: Define in [Link]


<servlet>
<servlet-name>ConfigServlet</servlet-name>
<servlet-class>[Link]</servlet-class>

<!-- Initialization Parameters -->


<init-param>
<param-name>adminEmail</param-name>
<param-value>admin@[Link]</param-value>
</init-param>

<init-param>
<param-name>appMode</param-name>
<param-value>production</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>ConfigServlet</servlet-name>
<url-pattern>/config</url-pattern>
</servlet-mapping>

Step 2: Read in Servlet using getInitParameter()


package [Link];

import [Link].*;
import [Link].*;
import [Link].*;

public class ConfigServlet extends HttpServlet {

@Override
public void init() throws ServletException {
String email = getInitParameter("adminEmail");
String mode = getInitParameter("appMode");
[Link]("Admin Email: " + email);
[Link]("App Mode: " + mode);
}

@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {

String email = getInitParameter("adminEmail");

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h3>Admin Email: " + email + "</h3>");
}
}
Aspect doGet() doPost()

✅2. Reading Init Parameters using Annotations

Example with @WebServlet and @WebInitParam


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

@WebServlet(
urlPatterns = {"/config"},
initParams = {
@WebInitParam(name = "adminEmail", value =
"admin@[Link]"),
@WebInitParam(name = "appMode", value =
"development")
}
)
public class ConfigServlet extends HttpServlet {

@Override
public void init() throws ServletException {
String email = getInitParameter("adminEmail");
String mode = getInitParameter("appMode");
[Link]("Email: " + email + ", Mode: " +
mode);
}

@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

String email = getInitParameter("adminEmail");


[Link]("text/html");
[Link]().println("<h2>Admin Email: " +
email + "</h2>");
}
}

Extra Tip: Servlet Context Init Parameters

For application-wide parameters (shared across all servlets), use context


params in [Link]:

<context-param>
<param-name>globalSetting</param-name>
<param-value>enabled</param-value>
</context-param>

Access with:

String global =
getServletContext().getInitParameter("globalSetting");

Session Tracking Approaches in Servlets


Aspect doGet() doPost()

Session tracking is the mechanism to maintain state across multiple


requests from the same client in a stateless HTTP protocol.

There are four main techniques used in servlets:

Technique Persistent? Client Support Needed? Secure?

1. URL Rewriting No No Less secure

2. Hidden Form Fields No No Less secure

3. Cookies Yes Yes (must be enabled) Moderate

4. Session API Yes No (server‐side) Most secure ✅

1. URL Rewriting

Appends session info directly to the URL as a query string.

Format:
[Link]

Example:
String sessionId = [Link]();
String rewrittenURL = [Link]("[Link]");
[Link](rewrittenURL);

 [Link]() automatically appends session ID if


cookies are disabled.

❗ Risk: Session ID is visible in browser address bar and logs.

2. Hidden Form Fields

Adds session information in a hidden <input> tag within an HTML form.

Example (form):
<form action="NextServlet" method="post">
<input type="hidden" name="sessionId" value="12345">
<input type="submit" value="Continue">
</form>

 Server must read the field in the next servlet:

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


Aspect doGet() doPost()

❗ Works only for form submissions, not for links.

3. Cookies

Stores session data on the client side in small text files.

Example: Set and Read Cookie

Set Cookie:

Cookie cookie = new Cookie("username", "john");


[Link](3600); // 1 hour
[Link](cookie);

Read Cookie:

Cookie[] cookies = [Link]();


for (Cookie c : cookies) {
if ([Link]().equals("username")) {
String user = [Link]();
}
}

✅Most common and convenient, but depends on client accepting cookies.

4. Session Tracking using HttpSession API (Recommended)

The servlet container creates and manages a server-side session object.

Example:
HttpSession session = [Link](); // Create or
retrieve session
[Link]("username", "john");

To retrieve it in another servlet:

HttpSession session = [Link](false); // Don't


create if it doesn't exist
String user = (String) [Link]("username");

 Each client gets a unique JSESSIONID, stored as:


o Cookie (by default)
o URL (if cookies are disabled)

✅Automatically handles session ID management


✅Secure and widely used
Aspect doGet() doPost()

✅Summary Table
Server‐ Client‐
Approach Pros Cons
side? side?

Exposes session in
URL Rewriting ❌ ✅ No need for cookies
URL

Hidden Form Works when cookies Only works with


❌ ✅
Fields are off forms

Can be disabled by
Cookies ✅ ✅ Transparent to users
user

Easy, secure, May fallback to


Session API ✅ ❌
recommended rewriting

You might also like