Unit 3 JV
Unit 3 JV
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.
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.
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.
Here’s a simple example of a servlet that responds with "Hello, World!" when accessed via a web
browser.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html")
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.
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).
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.
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.
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.*;
response.setContentType("text/html");
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
<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>
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
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
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.
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.
Feature Servlet
Definition A servlet is a Java class that handles HTTP requests and generates responses.
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.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@Override
synchronized (this) {
activeThreads++;
try {
e.printStackTrace();
synchronized (this) {
activeThreads--;
response.setContentType("text/html");
out.println("<html><body>");
out.println("<h1>Request processed!</h1>");
out.println("</body></html>");
<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
RunCopy code
1your-web-app/
2│
3├── WEB-INF/
4│ ├── web.xml
5│ └── classes/
6│ └── MultiThreadedServlet.class
1. Deploy the Application: Place the your-web-app directory in the webapps directory of your
servlet container (e.g., Apache Tomcat).
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