0% found this document useful (0 votes)
8 views8 pages

Unit 3 JV

A servlet is a Java class that handles HTTP requests and responses in web applications, enabling dynamic content generation and session management. The servlet life cycle includes stages such as loading, instantiation, initialization, request handling, and destruction, managed by the servlet container. Additionally, servlets can utilize the ServletContext for application-wide parameters and resource access, and can handle exceptions through various methods, distinguishing them from JavaServer Pages (JSP) which focus more on presentation.

Uploaded by

Rajnish Jha
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)
8 views8 pages

Unit 3 JV

A servlet is a Java class that handles HTTP requests and responses in web applications, enabling dynamic content generation and session management. The servlet life cycle includes stages such as loading, instantiation, initialization, request handling, and destruction, managed by the servlet container. Additionally, servlets can utilize the ServletContext for application-wide parameters and resource access, and can handle exceptions through various methods, distinguishing them from JavaServer Pages (JSP) which focus more on presentation.

Uploaded by

Rajnish Jha
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
You are on page 1/ 8

What is a Servlet?

A servlet is a Java class that runs on a web server and is used to handle requests and responses in a
web application. Servlets are part of the Java EE (Enterprise Edition) specification and are designed to
extend the capabilities of servers that host applications accessed via a request-response
programming model. They are primarily used to create dynamic web content, process user input,
and manage session data.

How Does a Servlet Handle HTTP Requests and Responses?

1. Request Handling: When a client (such as a web browser) sends an HTTP request to the
server, the server routes this request to the appropriate servlet based on the URL pattern
defined in the web application's deployment descriptor (web.xml) or through annotations.

2. Processing the Request: The servlet processes the request using


the HttpServletRequest object, which contains information about the request, such as
parameters, headers, and the request method (GET, POST, etc.).

3. Generating a Response: After processing the request, the servlet generates a response using
the HttpServletResponse object. This object allows the servlet to set response headers,
content type, and write the response body.

4. Sending the Response: Finally, the servlet sends the response back to the client, which is
typically rendered by the web browser.

Example of a Simple Servlet

Here’s a simple example of a servlet that responds with "Hello, World!" when accessed via a web
browser.

1. Create the Servlet Class

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class HelloWorldServlet extends HttpServlet {

// Override the doGet method to handle GET requests

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Set the content type of the response

response.setContentType("text/html")

// Get the output stream to write the response

PrintWriter out = response.getWriter()

// Write the response content

out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");

out.println("</body></html>");

The servlet life cycle is a series of stages that a servlet goes through from its creation to its
destruction. Understanding the servlet life cycle is crucial for developing robust web applications
using Java Servlets. The life cycle is managed by the servlet container (such as Apache Tomcat), which
is responsible for loading, instantiating, initializing, and managing the servlet.

Stages of the Servlet Life Cycle

1. Loading:

 The servlet container loads the servlet class into memory. This can happen when the
server starts up or when the servlet is first requested by a client.

2. Instantiation:

 The servlet container creates an instance of the servlet class using the default
constructor. This instance will handle all requests to that servlet.

3. Initialization:

 After instantiation, the servlet container calls the init() method of the servlet. This
method is used for one-time initialization tasks, such as setting up resources (e.g.,
database connections, configuration parameters).

 The init() method receives a ServletConfig object as a parameter, which contains


initialization parameters and a reference to the servlet context.

4. Request Handling:

 The servlet is now ready to handle client requests. For each request, the servlet container
creates a new thread and calls the service() method of the servlet.

 The service() method determines the type of request (GET, POST, etc.) and delegates the
request to the appropriate method (doGet(), doPost(), etc.).

5. Destruction:

 When the servlet is no longer needed (e.g., the server is shutting down or the servlet is being
removed), the servlet container calls the destroy() method.

 This method is used to release resources and perform cleanup tasks, such as closing
database connections or stopping background threads.

Summary of the Servlet Life Cycle

 Loading: The servlet class is loaded into memory.

 Instantiation: An instance of the servlet is created.


 Initialization: The init() method is called for one-time setup.

 Request Handling: The service() method is called for each request, which in turn
calls doGet(), doPost(), etc.

 Destruction: The destroy() method is called for cleanup before the servlet is removed.

Write a program for a simple servlet.

Step 1: Create the Servlet Class

Create a Java class that extends HttpServlet and overrides the doGet method to handle GET
requests.

HelloWorldServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class HelloWorldServlet extends HttpServlet {

// Override the doGet method to handle GET requests

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Set the content type of the response

response.setContentType("text/html");

// Get the output stream to write the response

PrintWriter out = response.getWriter();

// Write the response content

out.println("<html><body>");

out.println("<h1>Hello, World!</h1>");

out.println("</body></html>");

Step 2: Configure the Servlet in web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee

http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">

<servlet>

<servlet-name>HelloWorldServlet</servlet-name>

<servlet-class>HelloWorldServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloWorldServlet</servlet-name>

<url-pattern>/hello</url-pattern>

</servlet-mapping>

</web-app>

Handling HTTP requests and responses in a servlet involves using


the HttpServletRequest and HttpServletResponse objects provided by the Java Servlet API. These
objects allow you to access request data (such as parameters, headers, and attributes) and to
construct the response that will be sent back to the client.

Steps to Handle HTTP Requests and Responses

1. Extend HttpServlet: Create a servlet class that extends HttpServlet.

2. Override the doGet() or doPost() Method: Depending on the type of request (GET or POST),
override the appropriate method to handle the request.

3. Access Request Data: Use the HttpServletRequest object to retrieve data sent by the client.

4. Construct the Response: Use the HttpServletResponse object to set the response content
type, headers, and write the response body.

5. Send the Response: The servlet container automatically sends the response back to the
client

What is the purpose of the ServletContext object? Give an example.

The ServletContext object is an interface provided by the Java Servlet API that allows servlets to
interact with the web application environment in which they are running. It provides a way for
servlets to access application-wide parameters, resources, and attributes. The ServletContext is
shared among all servlets in a web application, making it useful for sharing data and configuration
settings.
Purpose of ServletContext

1. Application-Wide Parameters: Servlets can retrieve initialization parameters defined in


the web.xml file or through annotations. These parameters can be used to configure the
behavior of the application.

2. Resource Access: Servlets can access resources such as files, images, and other data stored
in the web application directory.

3. Attribute Sharing: Servlets can store and retrieve attributes in the ServletContext, allowing
different servlets to share data.

4. Logging: The ServletContext provides methods for logging messages, which can be useful for
debugging and monitoring the application.

5. Context Path: It provides information about the context path of the web application, which
can be useful for constructing URLs.

Handling exceptions in a servlet is crucial for ensuring that your web application can gracefully
manage errors and provide meaningful feedback to users. There are several ways to handle
exceptions in a servlet, including using try-catch blocks, defining error pages in the web.xml file, and
implementing the error method.

Methods to Handle Exceptions in a Servlet

1. Using Try-Catch Blocks: You can wrap your servlet code in try-catch blocks to catch specific
exceptions and handle them accordingly.

2. Using Error Pages: You can define error pages in the web.xml file that will be displayed when
specific exceptions occur or when a specific HTTP error status is returned.

3. Using the @WebServlet Annotation: If you are using annotations, you can specify error
pages directly in the servlet class.
What is the difference between a servlet and JSP? Give an example.

Servlets and JavaServer Pages (JSP) are both technologies used in Java web applications, but they
serve different purposes and have different characteristics. Here’s a breakdown of the key differences
between servlets and JSP, along with examples for each.

Key Differences Between Servlets and JSP

Feature Servlet

Definition A servlet is a Java class that handles HTTP requests and generates responses.

Syntax Written in pure Java code.

Development More complex and verbose, as it requires writing Java code for HTML generation.

Use Case Best suited for handling business logic and processing requests.

Compilation Compiled into a servlet class.

Separation of Concerns Less separation between presentation and business logic.

Write a program for servlets with multiple threads

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class MultiThreadedServlet extends HttpServlet {

private int activeThreads = 0;

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

synchronized (this) {

activeThreads++;

// Simulate a long-running task

try {

Thread.sleep(5000); // Simulate a task that takes 5 seconds


} catch (InterruptedException e) {

e.printStackTrace();

synchronized (this) {

activeThreads--;

// Set the content type of the response

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body>");

out.println("<h1>Request processed!</h1>");

out.println("<p>Active threads: " + activeThreads + "</p>");

out.println("</body></html>");

Step 2: Configure the Servlet in web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee

http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

version="3.1">

<servlet>

<servlet-name>MultiThreadedServlet</servlet-name>

<servlet-class>MultiThreadedServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>MultiThreadedServlet</servlet-name>

<url-pattern>/multiThread</url-pattern>

</servlet-mapping>

</web-app>
Step 3: Compile the Servlet

Make sure you have the Java Development Kit (JDK) installed and set up. Compile the servlet class
using the following command in the terminal:

bash

RunCopy code

1javac MultiThreadedServlet.java

Step 4: Create the Directory Structure

Create the following directory structure for your web application:

RunCopy code

1your-web-app/

2│

3├── WEB-INF/

4│ ├── web.xml

5│ └── classes/

6│ └── MultiThreadedServlet.class

Step 5: Deploy the Web Application

1. Deploy the Application: Place the your-web-app directory in the webapps directory of your
servlet container (e.g., Apache Tomcat).

2. Start the Server: Start your servlet container (e.g., Tomcat).

Step 6: Access the Servlet

Open multiple browser tabs or use a tool like Postman to send multiple GET requests to the servlet:

RunCopy code

1http://localhost:8080/your-web-app/multiThread

You might also like