Java Servlet
1. Introduction to Servlet
A Servlet is a Java program that runs on a web server and is used to develop dynamic web
applications. It handles client requests (usually HTTP requests), processes them, and generates
dynamic responses (usually HTML).
Servlets run inside a Servlet Container such as:
Apache Tomcat
GlassFish
JBoss
2. Why Servlets?
Limitations of CGI:
Platform dependent
Slower performance (new process for each request)
Less efficient
Advantages of Servlets:
Platform independent (Java-based)
Better performance (thread-based)
Secure
Robust and scalable
Persistent (remains in memory)
3. Servlet Architecture
Client (Browser)
→ HTTP Request
→ Web Server
→ Servlet Container
→ Servlet
→ HTTP Response
→ Client
Servlet Container Responsibilities:
Load and initialize servlet
Manage life cycle
Handle request and response objects
Provide security
Manage multithreading
4. Servlet Life Cycle
The servlet life cycle is controlled by the servlet container.
1. Loading and Instantiation
Servlet class is loaded and instance is created.
2. Initialization – init()
Called once when servlet is first loaded.
public void init() throws ServletException
3. Service – service()
Handles client requests. Called for each request.
public void service(ServletRequest req, ServletResponse res)
4. Destruction – destroy()
Called once before servlet is removed.
1
public void destroy()
5. Types of Servlets
1. GenericServlet
Protocol-independent
Located in [Link] package
2. HttpServlet
Used for HTTP protocol
Located in [Link] package
Most commonly used
Common methods in HttpServlet:
doGet()
doPost()
doPut()
doDelete()
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>");
}
}
6. Servlet API Packages
1. [Link]
Contains:
Servlet
GenericServlet
ServletRequest
ServletResponse
ServletConfig
ServletContext
2. [Link]
Contains:
HttpServlet
HttpServletRequest
HttpServletResponse
HttpSession
2
Cookie
7. Handling Client Request
GET Request
Data sent through URL
Visible
Limited size
POST Request
Data sent in request body
More secure
No size limitation (practically)
Example (Form):
<form action="HelloServlet" method="post">
Name: <input type="text" name="username">
<input type="submit">
</form>
In servlet:
String name = [Link]("username");
8. Session Management in Servlet
HTTP is stateless. To maintain user data:
1. Cookies
Cookie c = new Cookie("user", "Jasvant");
[Link](c);
2. HttpSession
HttpSession session = [Link]();
[Link]("user", "Jasvant");
3. URL Rewriting
[Link]("[Link]");
9. Servlet Configuration
Deployment Descriptor ([Link])
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
Annotation-based Configuration
@WebServlet("/hello")
10. Advantages of Servlet
Fast performance
Platform independent
Secure
Reusable
Scalable
Object-oriented
3
11. Difference Between Servlet and JSP
Servlet JSP
Java code inside HTML HTML inside Java
Better for business logic Better for presentation
Compiled manually Automatically compiled
More complex for UI Easier for UI design
12. Applications of Servlet
Login systems
Online forms
E-commerce websites
Banking applications
Dynamic web content generation
How to Run Servlet in Apache Tomcat
Step 1: Install Required Software
1. Install JDK (Java Development Kit)
2. Download and install Apache Tomcat
3. Set environment variables:
o JAVA_HOME
o CATALINA_HOME
Step 2: Create Project Structure
Inside Tomcat folder:
apache-tomcat/
└── webapps/
└── MyApp/
├── [Link]
└── WEB-INF/
├── [Link] (optional if using annotation)
└── classes/
Step 3: Compile Servlet
Open Command Prompt:
cd path_to_your_servlet
javac -cp "C:\apache-tomcat\lib\[Link]" [Link]
Copy .class file into:
WEB-INF/classes/
Step 4: Start Tomcat Server
Go to:
apache-tomcat/bin
Run:
[Link]
Step 5: Run in Browser
Open browser and type:
[Link]
Or directly:
[Link]
4
Alternative Method: Using IDE (Easier for Students)
You can use:
Eclipse IDE
NetBeans
IntelliJ IDEA
Steps in IDE:
1. Create Dynamic Web Project
2. Add Tomcat Server
3. Create Servlet
4. Run on Server
5. Open in browser
Step-wise Servlet Development with Complete Example
The development of a servlet involves several steps:
1. Create the Servlet class
2. Compile the Servlet
3. Create [Link] (Deployment Descriptor) or use annotation
4. Deploy the Servlet on the server
5. Run the Servlet in a browser
Example: Simple Servlet Program
Step 1: Create Directory Structure
Create a web application folder inside the server directory of Apache Tomcat.
Tomcat
└── webapps
└── MyApp
└── WEB-INF
└── classes
Step 2: Create the Servlet Class
Create a Java file named [Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
5
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html>");
[Link]("<head><title>Servlet
Example</title></head>");
[Link]("<body>");
[Link]("<h2>Hello, Welcome to Servlet
Programming</h2>");
[Link]("<p>This page is generated by a
Servlet.</p>");
[Link]("</body>");
[Link]("</html>");
}
}
Explanation
HttpServlet → Base class used to create servlets
doGet() → Method used to handle HTTP GET requests
HttpServletRequest → Used to receive client request
HttpServletResponse → Used to send response
PrintWriter → Used to display output in browser
Step 3: Compile the Servlet
Compile the servlet using the servlet library.
Example command:
javac -classpath "C:\Tomcat\lib\[Link]"
[Link]
After compilation:
[Link]
Place this file in:
WEB-INF/classes
Step 4: Create Deployment Descriptor ([Link])
Create a [Link] file inside WEB-INF
6
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Explanation
servlet-name → Name of servlet
servlet-class → Java class file
url-pattern → URL used to access servlet
Step 5: Deploy the Application
Project structure should look like this:
MyApp
└── WEB-INF
├── classes
│ └── [Link]
└── [Link]
Place MyApp inside:
Tomcat/webapps
Step 6: Start the Server
Start Apache Tomcat server.
Step 7: Run the Servlet in Browser
Open browser and type:
[Link]
Output
7
The browser will display:
Hello, Welcome to Servlet Programming
This page is generated by a Servlet.
Working of Servlet
1. Client sends request from browser
2. Web server receives the request
3. Servlet container loads the servlet
4. Servlet processes the request
5. Response is sent back to the browser