Sitemap

Guide to Servlet in Java

55 min readOct 16, 2024

--

Press enter or click to view image in full size

What are Servlets?

- Servlets are Java-based web technologies that enable the creation of dynamic web applications. They run on the server side and handle the logic required to respond to requests from clients, usually web browsers.

- Servlets are used to develop web applications that can be accessed through a browser. Sun Microsystems originally developed Servlets (now managed by Oracle).

OR

A Servlet is a Java class that extends the capabilities of servers that host web applications. It responds to incoming requests (usually HTTP requests from web browsers or clients) and generates a response, often in HTML format, to send back to the client.

What is a Web Application?

- A web application is software hosted on a server that users can access using a browser over the internet or an intranet.

- In web applications, the server hosts all application logic, and the clients interact with it using a browser interface. This approach allows centralized data handling, making it easier to manage and update.

Components in Web Applications

1. Client-side components: These are developed using technologies like HTML, XHTML, JSP (Java Server Pages), JavaScript, CSS, etc. They define how the content is presented to the user in the browser.

2. Server-side components: These are developed using technologies like Servlets, JSP, Filters, and more. Server-side components handle the business logic, data processing, and other backend operations of the web application.

How Web Requests Work

- When you enter a URL in a browser, the browser sends a request to the DNS server to resolve the domain name to an IP address.

- Once the IP address is found, the request is forwarded to the appropriate server hosting the web application.

- The server processes the request and sends back a response to the client (browser), which is then displayed to the user.

- Servers determine the client’s IP address from the HTTP request to track user sessions or send customized responses.

Versions of Servlets

The evolution of the Servlets API has happened over different versions of Java EE:

1. Servlets 2.2 — Released with J2EE 1.2

2. Servlets 2.3 — Released with J2EE 1.3

3. Servlets 2.4 — Released with J2EE 1.4

4. Servlets 2.5 — Released with JEE 5

5. Servlets 3.0 — Released with JEE 6

6. Servlets 3.1 — Released with JEE 7

Each version of the Servlets API brings new features, improvements, and updates to enhance web application development.

Types of Applications

1. Standalone Applications: These are traditional software applications that run on a single computer. Examples include MS Word, music players, etc. The main drawback is that they require installation on each machine, and data sharing is not possible.

2. Client-Server Applications: These applications have two components: the server-side application and the client-side application installed on multiple machines. Examples include chat applications like Yahoo Messenger. Although data sharing is possible, client software must be maintained on each machine.

3. Web Applications: These applications solve the problems of client-server applications. They run on a central server, and users access them using a web browser. Examples include Gmail, Google Maps, etc. Web applications can be implemented using technologies like Servlets, JSP, and more. Maintenance is easier since updates only need to be done on the server.

4. Distributed Applications: These applications are designed to work across multiple servers or locations, allowing businesses to share information with partners in real time.

5. Enterprise Applications: These are large-scale software systems designed to support an organization’s core business processes. They are usually integrated with other software systems to ensure seamless business operations.

Static vs. Dynamic Web Applications

- Static Web Applications: These have a fixed view, and the content remains the same for all users. Static web pages are developed using HTML and do not involve data processing or interaction.

- Dynamic Web Applications: These allow users to interact with the server and send data that is processed to produce dynamic responses. Servlets are often used to create these applications.

General Technical Terms Explained

1. Web Server: Software that handles HTTP requests from clients and sends back HTTP responses. Examples include Apache Server, IIS (Internet Information Services).

2. Web Client: Software (typically a web browser) that makes HTTP requests to a web server and receives responses.

3. Web Container: Also known as a Servlet container, this is the component within the web server that manages the lifecycle of Servlets and JSPs. It handles low-level tasks like request handling, security, resource management, and more.

4. HTTP (Hypertext Transfer Protocol): Protocol used for communication between the client and the server.

5. TCP/IP: Network protocol stack used for data communication. IP is responsible for addressing, while TCP manages the data transmission.

6. DNS (Domain Name Server): Translates domain names into IP addresses to locate servers on the internet.

Setting up Apache Tomcat

Prerequisites

1. Java Development Kit (JDK): Ensure you have JDK installed on your machine (version 8 or later).

2. Apache Tomcat: Download the latest version of Apache Tomcat from the [official website](https://tomcat.apache.org/).

Step 1: Install Apache Tomcat

1. Download Tomcat:

- Choose the appropriate distribution (usually the `.zip` or `.tar.gz` file).

2. Extract the Archive:

- Unzip or untar the downloaded file to a directory of your choice (e.g., `C:\apache-tomcat-9.0.xx` or `/usr/local/tomcat`).

3. Set Environment Variables (optional but recommended):

- JAVA_HOME: Point this to your JDK installation.

- CATALINA_HOME: Point this to your Tomcat installation directory.

For example, on Linux:

export JAVA_HOME=/path/to/jdk
export CATALINA_HOME=/path/to/tomcat

Step 2: Start Tomcat

1. Navigate to the `bin` directory of your Tomcat installation:

cd $CATALINA_HOME/bin

2. Start Tomcat:

- On Windows:

catalina.bat start

- On Linux/Unix:

./catalina.sh start

3. Open a web browser and go to `http://localhost:8080`. You should see the Tomcat welcome page.

Step 3: Create a Servlet

1. Create a Dynamic Web Project:

- Use an IDE like Eclipse or IntelliJ IDEA to create a new Dynamic Web Project.

2. Add Servlet:

- Create a new Java class that extends `HttpServlet` and override the `doGet` or `doPost` methods. Example:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<h1>Hello, World!</h1>");
}
}

Configure web.xml (if not using annotations):

  • If you’re not using servlet annotations, define your servlet in WEB-INF/web.xml:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

Step 4: Deploy the Servlet

1. Compile the Project: Make sure your project compiles without errors.

2. Create a WAR file: If using an IDE, it typically has an option to export the project as a WAR file.

3. Deploy the WAR:

- Place the WAR file in the `webapps` directory of your Tomcat installation.

4. Restart Tomcat:

- After placing the WAR file, restart Tomcat for the changes to take effect.

Step 5: Access the Servlet

1. Open a web browser and go to:

http://localhost:8080/your_project_name/hello

Replace `your_project_name` with the name of your WAR file (without the `.war` extension).

Troubleshooting Tips

- Check the `logs` directory in your Tomcat installation for any error messages.

- Ensure the servlet is correctly mapped and that there are no typos in your URL.

Java Servlets, classes and interfaces

Classes in Servlets

1. Servlet Class:

- The core of a servlet is a class that extends HttpServlet. This class provides methods to handle HTTP requests and responses.

- Commonly overridden methods include:

- doGet(HttpServletRequest request, HttpServletResponse response): Handles GET requests.

- doPost(HttpServletRequest request, HttpServletResponse response): Handles POST requests.

- Example:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello, World!</h1>");
}
}

2. Utility Classes:

- Often, utility classes are created to handle common tasks, such as database access, data processing, or configuration management.

Interfaces in Servlets

1. Servlet Interface:

- The Servlet interface defines the methods that must be implemented by any servlet class. It includes methods like init(), service(), and destroy().

- While developers typically extend HttpServlet, knowing the Servlet interface is important for understanding servlet lifecycle and behavior.

2. Other Interfaces:

- ServletConfig: This interface provides configuration information to the servlet. It allows access to initialization parameters and the servlet context.

- ServletContext: This interface provides information about the web application context. It allows servlets to interact with their environment, such as retrieving resources or attributes.

- HttpServletRequest and HttpServletResponse: These interfaces represent the request and response objects, respectively, enabling servlets to handle incoming requests and send responses back to clients.

Step-by-Step Guide to Developing and Running a Servlets 2.x-Based Web Application

1. Requirement Analysis

The application you’re building is a simple login page. When a user submits the form, the information will be processed by a servlet, which will display user details and some additional data.

2. Create a Dynamic Web Project in Eclipse

1. Open Eclipse.

2. Go to the menu and select File > New > Dynamic Web Project.

3. Provide the Project Name as lms1.

4. For the first-time setup:

- Click on the New Runtime button.

- Select Apache Tomcat 10.1 as the server and click on the Next button.

- Browse to the Tomcat Home Directory (e.g., E:\Tomcat 10.1) and click on Finish.

5. Click Finish again to create the project.

3. Project Directory Structure

Once the project is created, the default directory structure will look like this:

lms1

  • WebContent
  • login.html
  • src
  • com.lmsindia.servlets (package)
  • LoginServlet.java
  • WEB-INF
  • web.xml

4. Create the Login Page (login.html)

In the WebContent folder of your project, create a new HTML file named login.html. Here’s the code for the file:

<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>lms Test</h1>
<hr>
<form action="test.lms" method="post">
<table>
<tr>
<td>UserName:</td>
<td><input type="text" name="uname" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
</body>
</html>

This HTML form sends a POST request to the servlet when the user submits the form.

5. Create the Servlet Class (LoginServlet.java)

1. In the src folder, create a package named com.lmsindia.servlets.

2. Inside this package, create a Java class named lmsServlet.java. Use the following code:

package com.lmsindia.Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class lmsServlet extends HttpServlet {
String phone;
String email;
String state;
String country;
public void init(ServletConfig sc) throws ServletException {
System.out.println("lmsServlet - init()");
// Config parameters
phone = sc.getInitParameter("Phone");
email = sc.getInitParameter("Email");
// Context parameters
ServletContext ctx = sc.getServletContext();
state = ctx.getInitParameter("State");
country = ctx.getInitParameter("country");
}
protected void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
System.out.println("lmsServlet - service()");

// Request parameter
String un = req.getParameter("uname");

// Display parameters
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>Username: " + un + "</h1>");
out.println("<h1>Phone: " + phone + "</h1>");
out.println("<h1>Email: " + email + "</h1>");
out.println("<h1>State: " + state + "</h1>");
out.println("<h1>Country: " + country + "</h1>");
}
public void destroy() {
System.out.println("lmsServlet - destroy()");
}
}

This servlet retrieves and displays request parameters (username) as well as initialization and context parameters.

6. Update the Deployment Descriptor (web.xml)

In the WEB-INF folder, open the web.xml file and update it as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>State</param-name>
<param-value>UTTAR PRADESH</param-value>
</context-param>
<context-param>
<param-name>country</param-name>
<param-value>INDIA</param-value>
</context-param>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>com.lmsindia.Servlets.lmsServlet</servlet-class>
<init-param>
<param-name>Email</param-name>
<param-value>som@lmsindia.org</param-value>
</init-param>
<init-param>
<param-name>Phone</param-name>
<param-value>33333</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test.lms</url-pattern>
</servlet-mapping>
</web-app>

This file defines the servlet configuration, context parameters, and servlet mappings. It maps requests to /test.lms to the lmsServlet.

7. Deploy and Run the Project on Tomcat

1. Right-click on your project (lms1) in Eclipse.

2. Select Run As > Run on Server.

3. Choose Apache Tomcat 6.0 as the server and click Finish.

This step will deploy your web application to Tomcat and start the server.

8. Access the Web Application

- Open a web browser.

- Enter the URL: http://localhost:9999/lms1/login.html

- You should see the login form. Enter a username and submit the form to see the output from the servlet.

Summary of Required Files

1. Login.html: The HTML page that collects user input.

2. web.xml: The deployment descriptor that configures the servlet and mappings.

3. lmsServlet.java: The servlet class that handles the HTTP request and response.

Creating a Simple Servlet using annotaions:

Step 1: Create the Servlet Class

Here is a basic example of a servlet that generates a simple “Hello, World!” response.

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/hello") // URL pattern
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Write output to the client
response.getWriter().println("<h1>Hello, World!</h1>");
}
}

Explanation:

- @WebServlet(“/hello”): This annotation maps the servlet to the URL pattern /hello.

- doGet() Method: Handles HTTP GET requests. When a client sends a request to the URL /hello, this method is executed.

- response.setContentType(“text/html”): Sets the response’s content type to HTML.

- response.getWriter().println(): Sends an HTML response back to the client.

Step 3: Deploy the Servlet

To deploy the servlet, you need to package it into a WAR (Web Application Archive) file or directly place it in the webapps directory of Tomcat.

1. Folder Structure for manual deployment:

webapps/
└── your_app_name/
├── WEB-INF/
│ ├── web.xml
│ └── classes/
│ └── HelloServlet.class

2. Configuration in web.xml:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">

<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>

This web.xml file configures your servlet with the name HelloServlet and maps it to the URL /hello.

Step 4: Access the Servlet

- Start the Apache Tomcat server.

- Open your web browser and visit http://localhost:8080/your_app_name/hello.

You should see the response: Hello, World!

Servlet Instance Creation

1. Default Behavior:

- By default, a servlet instance is created when the first client request is received.

- Only one instance of the servlet is created, and it handles all client requests using multiple threads.

2. Eager Initialization:

- If you want a servlet instance to be created when the server or container starts (before any request is received), you can configure it using the following options:

In web.xml:

<servlet>
...
<load-on-startup>X</load-on-startup>
</servlet>

Using Annotations:

@WebServlet(urlPatterns = {"/example"}, loadOnStartup = X)

- X is an integer value that determines the order of initialization. Lower values are given higher priority.

Parameters in Servlets

Parameters are key-value pairs used to pass information to a servlet. There are three types of parameters:

1. ServletRequest Parameters:

- These parameters are sent from the client to the server as part of the HTTP request.

- Useful for handling data entered by users in web forms.

Example of retrieving request parameters:

String firstName = req.getParameter("fname");
String lastName = req.getParameter("lname");

2. ServletConfig Parameters:

- These parameters are specific to a particular servlet and are defined in the web.xml file or using annotations.

- They are useful for data that is common to all users of a specific servlet.

In web.xml:

<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.lmsindia.servlets.HelloServlet</servlet-class>
<init-param>
<param-name>email</param-name>
<param-value>hellosom@lmsindia.org</param-value>
</init-param>
</servlet>

Accessing ServletConfig parameters:

String email = config.getInitParameter("email");

3. ServletContext Parameters:

- These parameters are shared across all servlets in the web application.

- They are useful for data that needs to be accessed by multiple servlets.

Defining context parameters in web.xml:

<context-param>
<param-name>website</param-name>
<param-value>www.lmsindia.org</param-value>
</context-param>

Accessing ServletContext parameters:

String website = context.getInitParameter("website");

Explanation of the Code

Login.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>THIS IS INDEX HTML</h1>
<form action="hello.lms">
<h2>Enter Name</h2>
<input type="text" name="fname">
<br />
<input type="submit" value="Hello Test">
</form>
<form action="hai.lms">
<h2>Enter Phone</h2>
<input type="text" name="phone">
<br />
<input type="submit" value="Hai Test">
</form>
</body>
</html>

Web.xml

<display-name>lms2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>website</param-name>
<param-value>www.lmsindia.org</param-value>
</context-param>
<servlet>
<servlet-name>helloSevlet</servlet-name>
<servletclass>com.lmsindia.servlet.HelloServlet</servletclass>
<init-param>
<param-name>email</param-name>
<param-value>hellosom@lmsindia.org</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>helloservlet</servlet-name>
<url-pattern>/hello.lms</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>haiservlet</servlet-name>
<servletclass>com.lmsindia.servlet.HaiServlet</servletclass>
<init-param>
<param-name>email</param-name>
<param-value>haisom@lmsindia.org</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>haiservlet</servlet-name>
<url-pattern>/hai.lms</url-pattern>
</servlet-mapping>undefined</web-app>

Example Servlets

1. HelloServlet.java:

package com.lmsindia.servlet;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
ServletConfig cfg = null;
@Override
public void init(ServletConfig config) throws ServletException {
this.cfg = config; // Corrected to use 'config' instead of 'cfg'
System.out.println("init() method of HelloServlet");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
System.out.println("service() method of HelloServlet");
String fname = req.getParameter("fname");
String phone = req.getParameter("phone");
Writer out = res.getWriter();
res.setContentType("text/html");
out.write("<h1>Response from HelloServlet</h1>");
out.write("<hr/>Request Parameters");
out.write("<br/>Fname: " + fname);
out.write("<br/>Phone: " + phone);
out.write("<hr/>Servlet Config Parameters");
String eml = cfg.getInitParameter("email");
out.write("<br/>" + cfg);
out.write("<br/>Email: " + eml);
out.write("<hr/>Servlet Context Parameters");
ServletContext ctx = cfg.getServletContext();
String web = ctx.getInitParameter("website");
out.write("<br/>" + ctx);
out.write("<br/>Web: " + web);
}
}

This servlet handles requests and reads parameters from the HTTP request, ServletConfig, and ServletContext.

- It retrieves data like fname and phone from the request, email from ServletConfig, and website from ServletContext.

2. HaiServlet.java:

package com.lmsindia.servlet;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HaiServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
System.out.println("service() method of HelloServlet");
String fname = req.getParameter("fname");
String phone = req.getParameter("phone");
Writer out = res.getWriter();
res.setContentType("text/html");
out.write("<h1>Response from HelloServlet</h1>");
out.write("<hr/>Request Parameters");
out.write("<br/>Fname: " + fname);
out.write("<br/>Phone: " + phone);
out.write("<hr/>Servlet Config Parameters");
ServletConfig cfg = getServletConfig();
String eml = cfg.getInitParameter("email");
out.write("<br/>" + cfg);
out.write("<br/>Email: " + eml);
out.write("<hr/>Servlet Context Parameters");
ServletContext ctx = cfg.getServletContext();
String web = ctx.getInitParameter("website");
out.write("<br/>" + ctx);
out.write("<br/>Web: " + web);
}
}

- Similar to HelloServlet, but handles different parameters and requests.

Key Points

- init() method:

- It initializes the servlet instance when it is created, either upon the first request or during server startup (if specified).

- If you override the init() method without calling super.init(config), the ServletConfig will not be initialized.

- Servlet Lifecycle:

- init(): Called once when the servlet is created.

- service(): Called for every request to handle the logic.

- destroy(): Called before the servlet instance is destroyed.

Servlet Lifecycle Overview

The servlet lifecycle includes three main phases:

1. Initialization (Container Startup)

2. Request Processing

3. Destruction (Container Shutdown)

1. Initialization Phase (Container Startup)

When the server starts, the following steps occur:

1. Reading the web.xml: The container reads the deployment descriptor (web.xml) and stores its data in memory using a parser. If any error occurs in web.xml, the container stops the initialization process and cannot handle requests.

2. Servlet Context Creation:

- The container creates a ServletContext object, initializing it with context parameters defined in the web.xml.

- The context object is shared among all servlets in the web application.

3. Thread Pool Creation: The container creates a thread pool to handle incoming requests efficiently.

4. Listener Initialization:

- All the listeners defined in web.xml are initialized. This involves loading the listener classes, creating instances, and performing any setup tasks specified.

5. Filter Initialization:

- All filters specified in the web.xml are initialized. This means the filter classes are loaded, instances are created, and initialization tasks are performed.

6. Servlet Initialization (load-on-startup):

- The container checks for servlets configured with the load-on-startup parameter.

- The HelloServlet has load-on-startup set to a positive value, so it will be initialized when the server starts.

- For HelloServlet, the container performs the following steps:

1. Loads the servlet class into memory.

2. Creates an instance of the servlet using the default constructor.

3. Creates a ServletConfig object with the servlet’s initialization parameters (city parameter).

4. Associates the ServletConfig object with the ServletContext object.

5. Calls the init() method of the servlet with the ServletConfig object, completing the initialization process.

- The HaiServlet does not have a load-on-startup parameter, so it will be initialized later when the first request is made.

2. Request Processing Phase

Case 1: First Request to HelloServlet

1. URL Pattern Matching: The container matches the incoming URL (/hello.lms) with the servlet mapping.

2. Thread Allocation: Since HelloServlet is already initialized, the container picks a thread from the thread pool.

3. Request and Response Creation:

- A ServletRequest object is created and populated with data from the client.

- A ServletResponse object is created to hold the response data.

4. Service Method Invocation:

- The service() method of the servlet is called with the ServletRequest and ServletResponse objects.

- The servlet processes the request and generates the response.

5. Response Delivery: The response is sent back to the client, and the request and response objects are destroyed.

6. Thread Return: The thread is returned to the thread pool for reuse.

Case 2: Second Request to HelloServlet

- The process is the same as Case 1 since HelloServlet is already initialized.

Case 3: First Request to HaiServlet

1. URL Pattern Matching: The container matches the URL (/hai.lms) with the servlet mapping.

2. Servlet Initialization: Since HaiServlet is not yet initialized, the container initializes it by:

- Loading the servlet class into memory.

- Creating an instance of the servlet.

- Creating a ServletConfig object with the initialization parameters.

- Associating the ServletConfig object with the ServletContext object.

- Calling the init() method of the servlet.

3. Thread Allocation: After initialization, a thread from the pool is assigned to handle the request.

4. Request and Response Creation: The ServletRequest and ServletResponse objects are created.

5. Service Method Invocation: The service() method of HaiServlet is invoked.

6. Response Delivery: The response is delivered to the client, and the request and response objects are destroyed.

7. Thread Return: The thread is returned to the thread pool.

Case 4: Second Request to HaiServlet

- The process is the same as the second request to HelloServlet since HaiServlet is now already initialized.

3. Destruction Phase (Container Shutdown)

When the server shuts down, the following steps occur:

1. Thread Pool Destruction: The container destroys the thread pool, stopping all threads.

2. Servlet Destruction:

- The container destroys each servlet by calling the destroy() method of each servlet instance.

- This ensures that the resources held by the servlet are properly released.

3. Filter Destruction: Each filter is destroyed by invoking its destroy() method.

4. Listener Destruction: All listeners are destroyed in this phase, releasing any resources they hold.

5. Session Object Cleanup: Any active session objects are destroyed.

Summary of the Lifecycle

1. Container Startup:

- Reads web.xml, initializes context, listeners, filters, and servlets with load-on-startup.

2. Request Processing:

- Servlets handle client requests, with the service method being executed for each request.

3. Container Shutdown:

  • Proper cleanup of resources, threads, servlets, filters, listeners, and session objects.

RequestDispatcher Interface Overview

- RequestDispatcher is an interface available in the javax.servlet package.

- It is used to forward a request from one resource (like a servlet, JSP, or HTML page) to another resource on the server or to include the content of one resource in another.

- This interface provides two key methods:

- forward(ServletRequest req, ServletResponse res): Forwards a request from one resource to another.

- include(ServletRequest req, ServletResponse res): Includes the content of a resource in the response.

forward() Method

- The forward() method is used to forward the request from:

- Servlet to HTML

- Servlet to JSP

- Servlet to another Servlet

- JSP to HTML

- JSP to another JSP

- JSP to a Servlet

- Only one forward() can be executed per request. If you try to invoke another forward after the response is committed, you will get a java.lang.IllegalStateException.

- It prevents response modification or writing content to the response stream after the forward operation.

Example Usage

RequestDispatcher rd = null;
rd = req.getRequestDispatcher("test.html");
rd.forward(req, res);

include() Method

- The include() method is used to include the response of one servlet or JSP in another servlet or JSP.

- Unlike forward(), you can have multiple include() statements within a servlet or JSP.

- The response stream remains open after the inclusion, so additional content can still be written.

Files Required for Servlet Example

Required Files for Program Example Using forward() Method

1. Index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>THIS IS INDEX HTML</h1>
<a href="test.lms">Test</a>
<br/>
</body>
</html>

2. web.xml

<web-app>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>helloservlet</servlet-name>
<servlet-class>com.lmsindia.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloservlet</servlet-name>
<url-pattern>/test.lms</url-pattern>
</servlet-mapping>
</web-app>

3. TestServlet.java

package com.lmsindia.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Writer out = res.getWriter();
out.write("<h1>Hi, Welcome to lms</h1>");
}
}

Required Files for Servlet Example Using include() Method

1. Index.html

<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<a href="showhome.lms">GO TO HOME</a>
</body>
</html>

2. Additional HTML files (Header.html, Footer.html, Menu.html, Home.html, etc.)

Each of these files contains simple HTML structure with content to be included, like:

<html>
<body>
<h2>Header Content</h2>
</body>
</html>

3. ShowHomeServlet.java

package com.lmsindia.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowHomeServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
RequestDispatcher rd1 = req.getRequestDispatcher("header.html");
rd1.include(req, res);

RequestDispatcher rd2 = req.getRequestDispatcher("menu.html");
rd2.include(req, res);

RequestDispatcher rd3 = req.getRequestDispatcher("home.html");
rd3.include(req, res);

RequestDispatcher rd4 = req.getRequestDispatcher("footer.html");
rd4.include(req, res);
}
}

Key Differences between forward() and include() Methods

- forward():

- Transfers control to another resource without returning to the original.

- Only one forward() is allowed per request.

- Response is not modifiable after forward() is executed.

- include():

- Includes the content of another resource within the response.

- Allows multiple include() statements.

- Response stream remains open for additional modifications.

Servlet Thread Models

Servlets in Java can be implemented using two main thread models:

1. Single Thread Model

2. Multi-Thread Model (default and preferred approach)

1. Single Thread Model

- The SingleThreadModel interface is a deprecated way to ensure that only one thread executes the servlet’s service() method at a time.

- Implementing this model means that the servlet container creates a new servlet instance for each request or uses a pool of instances to handle requests, which can lead to significant overhead and inefficiency.

- The SingleThreadModel interface has been deprecated in J2EE 1.4 due to performance concerns and better alternatives available through proper synchronization.

2. Multi-Thread Model (default)

- By default, servlets follow the multi-threaded model, where a single instance of the servlet handles all the requests.

- Each request is handled by a different thread, which allows multiple clients to access the servlet simultaneously.

- The servlet container manages threading, which is more efficient and provides better performance for handling concurrent requests.

Example: Single Thread Model Servlet

Required Files for Servlet 2.X Example

The example below demonstrates the use of the Single Thread Model with a servlet named TestServlet. The setup includes an HTML form, the servlet code, and the web configuration file.

1. Index.html

This HTML form allows the user to input a name and submit it to the servlet.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<title>Enter Name</title>
</head>
<body>
<form action="test.lms">
<h1>Enter Name</h1>
<br>
<input type="text" name="uname" />
<br>
<input type="submit" value="Check">
</form>
</body>
</html>

2. TestServlet.java

This servlet implements the SingleThreadModel interface to demonstrate how it handles requests in a synchronized manner.

package com.lmsindia.servlet;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet implements SingleThreadModel {
public TestServlet() {
System.out.println("**TestServlet Def Cons: " + this);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String uname = req.getParameter("uname");
Writer out = res.getWriter();
out.flush();
Thread currentThread = Thread.currentThread();
for (int i = 0; i < 10; i++) {
System.out.println(currentThread.getName() + "\t" + uname + "\t" + this);
out.write("<br/>" + currentThread.getName() + "\t" + uname + "\t" + this);
try {
Thread.sleep(1000); // Simulates a delay in processing
} catch (InterruptedException e) {
e.printStackTrace();
}
out.write("<h1>Hi " + uname + "<br/>Response from Server</h1>");
}
}
}

Explanation:

- This servlet uses the SingleThreadModel, meaning each request will be handled in a synchronized way, ensuring no two threads are executing the service method at the same time.

- The Thread.sleep(1000) statement adds a delay of 1 second to simulate a time-consuming operation.

- The servlet prints out the current thread name, the user input, and the servlet instance details to the response stream.

3. web.xml

The web.xml configuration file registers the servlet and maps it to a URL pattern.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/webapp_3_0.xsd"
id="WebApp_ID"
version="3.0">
<display-name>lms13</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.lmsindia.servlet.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/test.lms</url-pattern>
</servlet-mapping>
</web-app>

Key Points on Servlet Thread Models

- Multi-threaded model (default): Offers better performance and scalability by allowing a single instance of the servlet to handle multiple requests concurrently using multiple threads.

- SingleThreadModel (deprecated): Intended to simplify thread safety by serializing request handling but is not recommended due to performance drawbacks and higher resource consumption.

Creating a Servlet Class in Eclipse

1. Right-click on the src folder in the Eclipse project.

2. Select New -> Servlet.

3. Provide the following details:

- Package name: Specify the package where the servlet will reside.

- Class name: Enter the name of the servlet class.

4. Change the superclass if needed, then click Next.

5. Provide the name of the servlet and the URL mapping.

6. Optionally, add any required init-parameters.

7. Click Finish to create the servlet.

This process sets up the servlet with default method signatures and configurations, making it ready for development.

Understanding HttpServletRequest and HttpServletResponse

HttpServletRequest and HttpServletResponse are interfaces provided by the Java Servlet API that represent the HTTP request and response in a servlet-based application. They are used to handle client-server communication using the HTTP protocol.

HttpServletRequest

- Represents an HTTP request sent by the client to the server.

- It contains information about the request, such as parameters, headers, cookies, and other data sent by the client.

Structure of an HTTP Request

1. Headers: Information about the request, such as the content type, user agent, cookies, and more.

2. Body: The main data of the request, used mainly in POST requests.

How Data is Transmitted

- When using the GET method, parameters are sent as a query string in the URL:

http://localhost:9999/lms1/login.lms?username=som&password=lmsindia

- URL: http://localhost:9999/lms1/login.lms

- Context Path: /lms1

- Protocol: http

- Host: localhost

- Port: 9999

- Query String: username=som&password=lmsindia

- The data is visible in the URL.

- When using the POST method, parameters are placed in the request body:

- Data is not visible in the URL, making it more secure.

- Allows sending a larger amount of data compared to the GET method.

HttpServletResponse

- Represents the response sent by the server back to the client.

- It contains:

- Response Headers: Information about the response (e.g., content type, status code).

- Response Body: The actual content sent to the client (e.g., HTML, JSON).

Files Required for Program

1. Index.html

This HTML file contains a form that sends data using the POST method.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<title>Request & Response Example</title>
</head>
<body>
<center>
<h1>Request & Response Example</h1>
</center>
<form action="test.lms" method="post">
<h2>Enter Username</h2>
<input type="text" name="uname" />
<h2>Enter Password</h2>
<input type="password" name="password" />
<input type="submit" value="Test" />
</form>
</body>
</html>

2. TestServlet.java

The servlet code that processes the request and sends the response.

package com.lmsindia.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// 1. Request parameters
String un = req.getParameter("uname");
String pw = req.getParameter("password");
// 2. Display request parameters
PrintWriter out = res.getWriter();
out.println("<h1>Username: " + un);
out.println("<br>Password: " + pw);
out.println("<br>Request Headers");
// 3. Request Headers
Enumeration<String> e = req.getHeaderNames();
while (e.hasMoreElements()) {
String hn = e.nextElement();
String hv = req.getHeader(hn);
out.println("<br>" + hn + ": " + hv);
}
// 4. Locale information
out.println("<br>Locale: " + req.getLocale());
// 5. Other information
out.println("<br>Method: " + req.getMethod());
out.println("<br>RequestURI: " + req.getRequestURI());
out.println("<br>RequestURL: " + req.getRequestURL());
out.println("<br>Protocol: " + req.getProtocol());
out.println("<br>ContentLength: " + req.getContentLength());
out.println("<br>ContentType: " + req.getContentType());
out.println("<br>RemoteAddr: " + req.getRemoteAddr());
out.println("<br>RemotePort: " + req.getRemotePort());
out.println("<br>RemoteHost: " + req.getRemoteHost());
out.println("<br>ServerPort: " + req.getServerPort());
out.println("<br>ServerName: " + req.getServerName());
out.println("<br>QueryString: " + req.getQueryString());
out.println("<br>ServletPath: " + req.getServletPath());
out.println("<br>ContextPath: " + req.getContextPath());
}
}

3. web.xml

Configuration file that registers the servlet and maps it to a specific URL pattern.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/webapp_3_0.xsd"
id="WebApp_ID"
version="3.0">
<display-name>lms14</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.lmsindia.servlet.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/test.lms</url-pattern>
</servlet-mapping>
</web-app>

Key Points

- GET Method:

- Data is sent as part of the URL.

- Limited data transmission capability.

- Less secure since data is visible in the URL.

- POST Method:

- Data is sent in the request body.

- Supports unlimited data transmission.

- More secure since data is not visible in the URL.

Working with Command Prompt

1. Set up the development directory structure.

2. Create and edit the required files.

3. Set the classpath for servlet-api.jar to compile the servlet class.

- Example:

Set CLASSPATH=%CLASSPATH%;E:\Tomcat 6.0\lib\Servlet-api.jar;

4. Compile the servlet class and place the files in the required directory.

5. Deploy the application to the webapps directory of Tomcat.

6. Start the Tomcat server and test the application using a web browser with the following URL:

http://localhost:9999/lmsapp

Request Handling with HTTP

Servlets interact with the HTTP protocol through the following key methods and objects:

1. HttpServletRequest:
— Represents the client’s request and contains information such as request parameters, HTTP headers, and request methods.
— Provides methods to access request data:
— getParameter(String name): Retrieves a request parameter.
— getHeader(String name): Retrieves an HTTP header.
— getMethod(): Returns the HTTP method (e.g., GET, POST).
— getInputStream(): Retrieves the request body as an input stream.

2. HttpServletResponse:
— Represents the response that will be sent to the client and provides methods to set response headers, status codes, and the response body.
— Provides methods to construct the response:
— setContentType(String type): Sets the MIME type of the response.
— setHeader(String name, String value): Sets a response header.
— getWriter(): Returns a PrintWriter to write character data to the response body.
— getOutputStream(): Returns an OutputStream to write binary data to the response body.

3. Handling Different HTTP Methods

Servlets can handle different HTTP methods by overriding specific methods:

- doGet(HttpServletRequest req, HttpServletResponse resp):
— Handles HTTP GET requests, typically used to retrieve data from the server.
— Example:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("name");
resp.setContentType("text/plain");
resp.getWriter().write("Hello, " + name);
}

doPost(HttpServletRequest req, HttpServletResponse resp):
— Handles HTTP POST requests, typically used to submit data to the server.
— Example:

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String data = req.getParameter("data");
// Process the data
resp.setContentType("text/plain");
resp.getWriter().write("Data received");
}

- doPut(HttpServletRequest req, HttpServletResponse resp):
— Handles HTTP PUT requests, which are often used to update resources.

- doDelete(HttpServletRequest req, HttpServletResponse resp):
— Handles HTTP DELETE requests, which are used to delete resources.

4. Example of a Simple Servlet

Here’s an example of a basic servlet that handles a GET request:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write("<html><body><h1>Hello, World!</h1></body></html>");
}
}

5. Request and Response Flow

1. Client Request:
— A client (browser) sends an HTTP request to the server.

2. Servlet Invocation:
— The servlet container receives the request, maps it to the appropriate servlet based on the URL pattern, and calls the service() method of the servlet.

3. Processing Request:
— The servlet processes the request using the HttpServletRequest object and generates a response using the HttpServletResponse object.

4. Sending Response:
— The servlet writes the response content to the HttpServletResponse object.

5. Client Response:
— The server sends the HTTP response back to the client.

In summary, servlets work with the HTTP protocol by managing the lifecycle of servlets, handling requests and responses through HttpServletRequest and HttpServletResponse objects, and processing different HTTP methods to generate appropriate responses for the client.

7. What is the Role of the ServletConfig and ServletContext Interfaces?

In the servlet API, two important interfaces — ServletConfig and ServletContext — provide access to configuration information for servlets and the overall web application. Both are used to share data across the servlet and application scope, but they serve different purposes.

1. ServletConfig Interface

ServletConfig is used to configure a specific servlet. It provides information that is specific to that servlet, such as initialization parameters defined in the web.xml file or through annotations. Each servlet in a web application has its own ServletConfig object, which is created by the servlet container when the servlet is initialized.

Key Methods of ServletConfig:
— getInitParameter(String name): Retrieves the value of a specific initialization parameter for the servlet.
— getInitParameterNames(): Returns an Enumeration of all initialization parameter names.
— getServletContext(): Provides access to the ServletContext object, allowing the servlet to access shared resources.
— getServletName(): Returns the name of the servlet as defined in the web.xml or by annotation.

Example Usage of ServletConfig:

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/configExample")
public class ConfigExampleServlet extends HttpServlet {
private String adminEmail;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
// Retrieve initialization parameter from web.xml
adminEmail = config.getInitParameter("adminEmail");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Servlet Config Example</h1>");
out.println("<p>Admin Email: " + adminEmail + "</p>");
out.println("</body></html>");
}
}

When to Use ServletConfig:
— Use ServletConfig when you need to pass configuration parameters that are specific to a particular servlet (e.g., a database connection string, a file path, or an email address).

2. ServletContext Interface

ServletContext is used to share information across the entire web application. It represents the web application’s environment and can be used to access shared resources such as files, attributes, and initialization parameters that are global to the application. Unlike ServletConfig, there is only one ServletContext object per web application, and it is shared by all servlets in that application.

Key Methods of ServletContext:
— getInitParameter(String name): Retrieves the value of an initialization parameter that is global to the entire web application.
— getInitParameterNames(): Returns an Enumeration of all global initialization parameter names.
— getAttribute(String name): Retrieves an attribute that has been set in the servlet context.
— setAttribute(String name, Object object): Sets an attribute that can be shared across servlets.
— getResourceAsStream(String path): Retrieves a resource as an input stream (e.g., a file from the WEB-INF directory).
— getRealPath(String path): Converts a virtual path to a real path on the server’s filesystem.
— log(String message): Logs a message to the server’s log file.

Example Usage of ServletContext:

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/contextExample")
public class ContextExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
ServletContext context = getServletContext();

// Get a global initialization parameter
String supportEmail = context.getInitParameter("supportEmail");

// Set an attribute that can be shared across servlets
context.setAttribute("appName", "My Web Application");

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Servlet Context Example</h1>");
out.println("<p>Support Email: " + supportEmail + "</p>");
out.println("<p>Application Name: " + context.getAttribute("appName")
+ "</p>");
out.println("</body></html>");
}
}

When to Use ServletContext:
— Use ServletContext when you need to share data or configuration parameters across the entire web application.
— It is also used when you need to interact with resources at the application level (e.g., reading a file from WEB-INF or logging messages).

Differences Between ServletConfig and ServletContext:
— Scope:
— ServletConfig is specific to a single servlet.
— ServletContext is shared by all servlets in the web application.
— Initialization Parameters:
— ServletConfig provides initialization parameters specific to a servlet.
— ServletContext provides initialization parameters that are global to the entire application.
— Attributes:
— ServletConfig does not manage attributes.
— ServletContext allows you to set and get attributes that are shared across servlets.

Conclusion
— ServletConfig is used for servlet-specific configuration, while ServletContext is used for application-wide configuration and shared resources.
— They both provide a way to access initialization parameters, but at different scopes: servlet-specific vs. application-wide.

Introduction to JSP (Java Server Pages)

Java Server Pages (JSP) is a technology that enables the creation of dynamic web content using a combination of HTML and Java code. JSP is commonly used for developing web applications that generate dynamic content, allowing you to embed Java code directly within HTML pages.

Get Pratik T’s stories in your inbox

Join Medium for free to get updates from this writer.

Key Features of JSP

1. Combination of HTML and Java Code: JSP allows the mixing of HTML tags with Java code to create web pages with dynamic content.

2. JSP Processing: The web container processes the JSP file by converting it into a Servlet, which is then compiled and executed to generate the HTML response.

3. File Extension: JSP files have the .jsp extension.

4. Predefined Objects: JSP provides several built-in objects that can be accessed without any explicit creation. Some of these objects include:

- request: Represents the HttpServletRequest object.

- session: Represents the HttpSession object for session tracking.

- out: Represents the PrintWriter object for sending data to the response.

- application: Represents the ServletContext object.

JSP Scripting Elements

JSP uses scripting elements to allow Java code to be embedded within the HTML. Here are the primary types of scripting elements:

1. Scriptlet: Allows you to write Java code that is valid inside a method.

<%
// Java code here
int sum = 5 + 3;
%>

- The code inside <% %> will be executed as part of the Servlet’s service method.

2. Expression: Outputs the result of an expression to the response.

<%= sum %>

- The <%= %> syntax evaluates the expression and converts it to a string that is directly inserted into the HTML.

3. Directive: Used to define page-level settings such as importing classes, content type, etc.

<%@ page import="java.util.Date" %>

- Directives are used to import classes or set page properties.

Example JSP File (Index.jsp)

Below is an example of a simple JSP file that demonstrates the use of scriptlets, expressions, and directives.

<%@ page import="java.util.Date" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Example</title>
</head>
<body>
<h1>THIS IS INDEX JSP</h1>
<%
for (int i = 0; i < 5; i++) {
System.out.println(i); // prints to server console
out.write("<br>" + i); // writes to the web page
}
%>
<br>Current Time:
<%
Date dt = new Date();
out.write("<br>" + dt);
String str = "lms";
%>
<br>
<font color="red" size="5"><%= dt %></font>
<br>
<font color="red" size="5"><%= str %></font>
</body>
</html>

Working with Multiple JSP Pages

Sometimes, JSP pages interact with each other, passing data between them. Here’s an example using two JSP files: Index.jsp and Show.jsp.

Index.jsp

The Index.jsp file sets some attributes in the application context, which will be shared across multiple JSP pages.

<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Example</title>
</head>
<body>
<h1>THIS IS INDEX JSP</h1>
<%
String str = "lms";
application.setAttribute("MSG", str);
List<String> emails = new ArrayList<>();
emails.add("som@lms.com");
emails.add("Rahul@lms.com");
emails.add("Neha@lms.com");
application.setAttribute("EMAILS", emails);
%>
<a href="show.jsp">Show Data</a>
</body>
</html>

Show.jsp

The Show.jsp file retrieves the attributes set by Index.jsp and displays them on the page.

<%@ page import="java.util.List" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Show Data</title>
</head>
<body>
<h1>THIS IS SHOW JSP</h1>
<p>Message: <%= application.getAttribute("MSG") %></p>
<%
List<String> emails = (List<String>)application
.getAttribute("EMAILS");
for (String email : emails) {
%>
<font color="red"><br><%= email %></font>
<%
}
%>
</body>
</html>

Key Concepts in JSP

- Scripting elements allow embedding Java code in HTML.

- Directives are used to import classes or set properties for the JSP page.

- Predefined objects like request, response, session, and application are automatically available in JSP.

Advantages of JSP

1. Separation of Content and Logic: Easier to maintain than traditional Servlets because the presentation logic (HTML) is separated from the business logic (Java code).

2. Predefined Objects: JSP provides implicit objects to handle common tasks like session management and output generation.

3. Easy to Use: JSP code is easier to write and understand as compared to Servlets.

Conclusion

JSP provides a convenient way to create dynamic web pages by combining HTML with Java code. It simplifies web application development by separating the presentation layer from the business logic, making it a popular choice for building Java-based web applications.

Session Management in Web Applications

Session management is crucial in web applications because HTTP and web servers are stateless by nature. This means they treat each request as a new one without knowing if it comes from the same user or a different one. Session management helps to maintain user information across multiple requests.

Key Concepts of Session Management

1. Stateless Nature of HTTP: The HTTP protocol does not keep track of client interactions. Each request sent to the server is processed independently without any memory of previous requests.

2. Need for Sessions: In many applications like shopping carts, user authentication, or personalized content, it’s necessary to track the user’s activity, such as which items they have added to the cart or which pages they have visited.

3. Session: A session is a series of related requests and responses between a client and a server. Sessions store user-specific information so that it can be shared across multiple requests.

How Sessions Work

To maintain a session, the server uses a session ID to recognize the client. This session ID is generated when a session is created and is stored either in cookies or URL parameters. The server uses this ID to track the session.

To use sessions in a web application, the following two steps are performed:

1. Identifying the Client: Check if the client has an existing session or needs a new one.

2. Managing the Conversational State: Store and retrieve user-specific data throughout the session.

Using HttpSession in JSP/Servlet

- You can use the HttpServletRequest object to create or access the HttpSession object in JSP/Servlet.

- Methods to access the session object:

HttpSession sess = request.getSession();
HttpSession sess = request.getSession(boolean);

Example of Session Management Techniques

Session Management Techniques:

1. HttpSession (Most common way to store session data)

2. Cookies (Stores session ID in the client-side browser)

3. URL Rewriting (Carries session ID within the URL)

4. Hidden Fields (Uses hidden HTML fields to pass data between requests)

Example Program for Session Management in a Shopping Cart

Here’s a breakdown of a JSP/Servlet-based program for handling session management in a shopping cart application:

Directory:

/ShoppingCartApp
├── /src
│ ├── /com
│ │ └── /lmsindia
│ │ └── /servlets
│ │ ├── AddToCartServlet.java
│ │ ├── ShowCartServlet.java
│ │ ├── RemoveFromCartServlet.java
│ │ └── SearchBooksServlet.java
│ ├── /META-INF
│ │ └── context.xml
│ └── /WEB-INF
│ ├── web.xml
│ └── classes
│ └── (compiled .class files)
├── /WebContent
│ ├── /jsp
│ │ ├── index.jsp
│ │ ├── showbooks.jsp
│ │ ├── showcart.jsp
│ │ └── placeorder.jsp
│ ├── /css
│ │ └── styles.css (optional CSS files for styling)
│ ├── /images
│ │ └── (any image files used in the project)
│ └── /scripts
│ └── scripts.js (optional JavaScript files for client-side logic)
└── /lib
└── (external libraries or JAR files required for the project)

1. Index.jsp

This file serves as the entry point for the shopping cart application. It displays a form where users can select a category of books and search for them.

<%@ page language="java" contentType="text/html; charset=ISO8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>lms Bookstore</title>
</head>
<body>
<center>
<h1>lms Bookstore</h1>
<h2>Book Search</h2>
<form action="searchbooks.lms" method="post">
<table>
<tr><td><h2>Select Category</h2></td></tr>
<tr>
<td>
<select name="category">
<option value="java">Java</option>
<option value="Testing">Testing</option>
<option value=".NET">.NET</option>
<option value="SAP">SAP</option>
</select>
</td>
</tr>
<tr><td><input type="submit" value="SearchBooks"/></td></tr>
</table>
</form>
</center>
</body>
</html>

Explanation: This JSP page displays a simple dropdown form where users can select a category of books. Upon submission, the form directs the request to the searchbooks.lms servlet to handle the search logic.

2. Showcart.jsp

This file is responsible for displaying the items currently in the user’s shopping cart.

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=ISO8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>lms BookStore - Shopping Cart</title>
</head>
<body>
<center>
<h1>lms BookStore</h1>
<h2>Your Shopping Cart</h2>
</center>
<%
Object object = request.getAttribute("MSG");
if(object != null) {
%>
<br>
<center>
<font color="red" size="6"><%= object %></font>
</center>
<%
} else {
object = request.getAttribute("CART");
ArrayList<String> blist = (ArrayList<String>) object;
for(String bnm : blist) {
%>
<form action="removeformcart.lms" method="post">
<input type="hidden" name="bname" value="<%= bnm %>"/>
<font size="5"><%= bnm %> <input type="submit" value="Remove From Cart"/></font>
</form>
<%
}
}
%>
<br>
<center><a href="Placeorder.jsp">PLACE ORDER</a></center>
<center><br><a href="showbooks.jsp">ADD TO CART</a></center>
</body>
</html>

Explanation: This page displays the list of items in the shopping cart. If the cart is empty or if there’s an error message, it displays the corresponding message. It also provides links to place the order or add more items to the cart.

3. Showbooks.jsp

Displays the list of available books based on the category selection.

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html;charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<title>lms Bookstore - Available Books</title>
</head>
<body>
<center>
<h1>lms Bookstore</h1>
<h2>Book List</h2>
<font color="green" size="6">${ADDED}</font>
</center>
<br>
<% Object obj = request.getAttribute("MSG");
if (obj != null) {
%>
<br>
<center>
<font color="red" size="6"><%= obj %></font>
<br><a href="index.jsp">GO TO SEARCH PAGE</a>
</center>
<%
} else {
obj = session.getAttribute("BOOKS");
ArrayList<String> blist = (ArrayList<String>) obj;
for (String bnm : blist) {
%>
<form action="addtocart.lms" method="post">
<input type="hidden" name="name" value="<%= bnm %>"/>
<font size="5"><%= bnm %> <input type="submit" value="ADD TO CART"/>
</font>
</form>
<%
}
}
%>
<br>
<form action="showcart.lms"><input type="submit" value="SHOW CART"></form>
</body>
</html>

Explanation: This page lists the books based on the selected category. It provides an option to add each book to the shopping cart.

4. Placeorder.jsp

This JSP page confirms the order placement and then invalidates the session.

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html;charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<title>Order Confirmation</title>
</head>
<body>
<center>
<h1>Bookstore</h1>
<h2>Your Order has been placed successfully</h2>
<%
session.invalidate();
%>
<br>
<a href="index.jsp">GO TO SEARCH PAGE</a>
</center>
</body>
</html>

Explanation: Once the order is placed, the session is invalidated to clear the user’s cart, and a success message is displayed.

5. Web.xml

Deployment descriptor that configures the servlet mappings and application settings.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Shopping Cart</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>SearchBooks</servlet-name>
<servlet-class>com.lmsindia.servlets.SearchBooksServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SearchBooks</servlet-name>
<url-pattern>/searchbooks.lms</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>AddToCartServlet</servlet-name>
<servlet-class>com.lmsindia.servlets.AddToCartServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddToCartServlet</servlet-name>
<url-pattern>/addtocart.lms</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ShowCartServlet</servlet-name>
<servlet-class>com.lmsindia.servlets.ShowCartServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowCartServlet</servlet-name>
<url-pattern>/showcart.lms</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>RemoveFromCartServlet</servlet-name>
<servlet-class>com.lmsindia.servlets.RemoveFromCartServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RemoveFromCartServlet</servlet-name>
<url-pattern>/removeformcart.lms</url-pattern>
</servlet-mapping>
</web-app>

Explanation: This file maps specific URLs to their corresponding servlets and defines the application’s welcome file, which is the page users see first when they access the application.

Summary of Session Management

- HttpSession is the most common method for managing sessions.

- Cookies and URL Rewriting can be used to maintain session IDs.

- Hidden Fields can be used in forms to pass data between requests.

Session management is vital for building user-specific experiences in web applications like e-commerce sites, where tracking the user’s state and data is necessary for personalized interactions.

Exploring HttpSession in Detail

HttpSession is an interface that allows server-side session tracking in Java-based web applications. It helps maintain user data across multiple requests. Here’s a quick overview of its primary methods and uses:

1. Creating a Session:

- HttpSession getSession() — Retrieves the current session or creates a new session if none exists.

- HttpSession getSession(boolean create) — Retrieves the current session, and if create is true, it creates a new session if none exists.

2. Storing and Retrieving Data from the Session:

- void setAttribute(String name, Object value) — Stores data in the session as an attribute.

- Object getAttribute(String name) — Retrieves the value of an attribute stored in the session.

- void removeAttribute(String name) — Removes an attribute from the session.

- Enumeration getAttributeNames() — Returns an enumeration of attribute names stored in the session.

3. Session Management:

- public String getId() — Returns the unique session ID.

- public boolean isNew() — Checks if the session is newly created.

- public void invalidate() — Destroys the session immediately.

- public void setMaxInactiveInterval(int seconds) — Sets the maximum inactive interval for a session before it expires.

- public long getLastAccessedTime() — Returns the last time the session was accessed.

- public long getCreationTime() — Returns the time the session was created.

Now, let’s take a look at the program files using HttpSession.

1. Index.jsp

This JSP page demonstrates the usage of the session to display the session ID and check if the session is new.

<%@page session="false" %>
<%@ page language="java" contentType="text/html;charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<title>Session Test</title>
</head>
<body>
<h1>
<br>Session ID: <%= session.getId() %>
<br>Is New Session: <%= session.isNew() %>
<br><a href="test.lms">TEST</a>
</h1>
</body>
</html>

Explanation:

- This page retrieves and displays the session ID and checks if the session is new using the methods session.getId() and session.isNew().

- The link redirects to the TestServlet when clicked.

2. Web.xml

This configuration file sets up the servlet mapping and session timeout settings.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>lms_20</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.lmsindia.servlet.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/test.lms</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>

Explanation:

- The servlet mapping binds the TestServlet to the URL pattern /test.lms.

- The <session-config> section sets the session timeout to 30 minutes. This means that if the session remains inactive for 30 minutes, it will be automatically invalidated.

3. TestServlet.java

This servlet demonstrates the creation of a session and the use of its properties.

package com.lmsindia.servlet;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession(); // Retrieves or creates a new session
Writer out = res.getWriter();
out.write("<h1><br>ID: " + session.getId());
out.write("<br>isNew: " + session.isNew());
// Checking if the session is new or already exists
}
}

Explanation:

- req.getSession() creates a new session if none exists or retrieves the current session.

- session.getId() displays the unique session identifier.

- session.isNew() checks if the session is newly created (returns true) or if it’s a pre-existing session.

Session Management Methods

To manage session expiration, you can use these methods:

1. Explicitly Destroying a Session:

session.invalidate();

This method destroys the session immediately.

2. Setting Session Timeout Interval:

session.setMaxInactiveInterval(int intervalInSeconds);

This sets the timeout interval, after which the session will expire if it remains inactive.

3. Session Timeout in Web.xml:

<session-config>
<session-timeout>30</session-timeout>
</session-config>

This setting in web.xml defines the timeout interval in minutes for all sessions in the web application.

Summary

This example illustrates the basics of session management using HttpSession in a Java web application:

- Session Tracking: Create, track, and manage user sessions.

- Session Attributes: Store and retrieve user-specific data in session attributes.

- Session Invalidation: Destroy sessions explicitly or automatically using timeouts.

This approach helps maintain state across multiple client requests in stateless HTTP connections, making it fundamental for web applications requiring user-specific interactions.

Servlet Scopes

Servlets provide three main scopes for managing data: Request Scope, Session Scope, and Context (or Application) Scope. Each scope defines the visibility and lifespan of the data stored within it.

1. Request Scope

- Definition: Data stored in the HttpServletRequest object.

- Accessibility: Accessible only for the duration of a single request. Once the request is completed (e.g., after a response is sent to the client), the data is no longer available.

- Use Case: Ideal for temporary data that is only needed while processing a specific request, such as form input.

Methods:

- void setAttribute(String name, Object value): Stores an attribute in the request.

- void removeAttribute(String name): Removes an attribute from the request.

- Object getAttribute(String name): Retrieves an attribute from the request.

- Enumeration<String> getAttributeNames(): Gets the names of all attributes.

2. Session Scope

- Definition: Data stored in the HttpSession object.

- Accessibility: Accessible across multiple requests made by the same user during a session. A session typically lasts until the user logs out or the session times out.

- Use Case: Suitable for user-specific data that should persist across requests, such as user preferences or login status.

Methods:

- Similar to request scope but using the session object instead.

3. Context (or Application) Scope

- Definition: Data stored in the ServletContext object.

- Accessibility: Accessible by all users across multiple requests. The data persists as long as the application is running, making it suitable for shared resources or configuration settings.

- Use Case: Best for global data that needs to be accessed by multiple users, like application-wide settings or shared data.

Methods:

- Same as above but using the context object.

Summary

- Request Scope: Temporary data for a single request.

- Session Scope: User-specific data across multiple requests within a session.

- Context/Application Scope: Shared data available to all users and requests during the application’s lifecycle.

These scopes help manage data effectively in web applications, ensuring that data is available where and when it’s needed while also managing memory efficiently.

Exploring Cookies

Cookies are small pieces of data stored on the client-side, which help in maintaining session state between HTTP requests. They are used to store user-specific information like session IDs, preferences, or tracking data. Here are the key points:

1. Creating a Cookie:

- A cookie is created on the server with a name and value:

Cookie ck = new Cookie("email", "som@lms.com");

- Cookies store information in key-value pairs, and both the name and value are strings.

2. Adding a Cookie to the Response:

- Once a cookie is created, it is added to the HTTP response to send it to the client:

response.addCookie(ck);

3. Accessing Cookies from a Request:

- Cookies that were stored on the client machine are sent back to the server with each HTTP request:

Cookie[] cookies = request.getCookies();
for (Cookie c : cookies) {
String cookieName = c.getName();
String cookieValue = c.getValue();
System.out.println(cookieName + ": " + cookieValue);
}

4. Removing Cookies:

- To remove a cookie from the client’s browser, set its maximum age to 0 and add it to the response:

Cookie c = new Cookie("cookieName", "");
c.setMaxAge(0);
response.addCookie(c);

Understanding JSESSIONID Cookie

The container manages sessions by using a special cookie named JSESSIONID. The process involves:

- Creating a cookie with the session ID when a session is created.

- Adding that cookie to the response to the client.

- Retrieving this cookie with subsequent requests to track the session.

Web Container’s Role in Session Management:

- The server generates a special cookie: JSESSIONID.

- It adds the JSESSIONID cookie to the response.

- It uses JSESSIONID to map the session ID to the corresponding session object.

Example Program Files

Let’s review the example files involved in demonstrating how to work with cookies in a Java web application.

1. Index.html

This file contains a form to add and remove cookies.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Cookie Example</title>
</head>
<body>
<h1>Cookie Example</h1>
<form action="add.lms" method="post">
<input type="text" name="bname" /><br>
<input type="submit" value="ADD" />
</form>
<hr>
<form action="remove.lms" method="post">
<h2>Enter Book Name</h2>
<input type="text" name="bname" /><br>
<input type="submit" value="Remove" />
</form>
</body>
</html>

2. AddServlet.java

This servlet handles adding a new cookie.

package com.lmsindia.servlet;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class AddServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Writer out = res.getWriter();
String bnm = req.getParameter("bname");
Cookie c1 = new Cookie(bnm, null);
res.addCookie(c1);
out.write("<h1>" + bnm + " added</h1>");
Cookie cs[] = req.getCookies();
if (cs == null) {
out.write("<h2>You are a new client</h2>");
HttpSession sess = req.getSession();
} else {
boolean found = false;
for (Cookie c : cs) {
String nm = c.getName();
String val = c.getValue();
out.write("<h2>" + nm + ": " + val + "</h2>");
if (nm.equals("JSESSIONID")) found = true;
}
if (found) {
out.write("<h2>You are an existing client</h2>");
}
}
RequestDispatcher rd = req.getRequestDispatcher("index.html");
rd.include(req, res);
}
}

3. RemoveServlet.java

This servlet handles removing a cookie.

package com.lmsindia.servlet;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class RemoveServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String bnm = req.getParameter("bname");
Writer out = res.getWriter();
Cookie[] cs = req.getCookies();
if (cs == null) {
out.write("<h2>You are a new client</h2>");
HttpSession sess = req.getSession();
} else {
boolean found = false;
for (Cookie c : cs) {
String nm = c.getName();
if (nm.equals(bnm)) {
c.setMaxAge(0);
res.addCookie(c);
out.write("<h2>Cookie " + bnm + " removed</h2>");
} else {
out.write("<h2>" + nm + ": " + c.getValue() + "</h2>");
}
}
}
RequestDispatcher rd = req.getRequestDispatcher("index.html");
rd.include(req, res);
}
}

4. Web.xml

The web descriptor file with servlet mappings.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>lms22</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>AddServlet</servlet-name>
<servlet-class>com.lmsindia.servlet.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddServlet</servlet-name>
<url-pattern>/add.lms</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>RemoveServlet</servlet-name>
<servlet-class>com.lmsindia.servlet.RemoveServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RemoveServlet</servlet-name>
<url-pattern>/remove.lms</url-pattern>
</servlet-mapping>
</web-app>

When dealing with web applications, maintaining a session state between the client and the server is crucial. Cookies are a common method to store session information, but they aren’t always reliable because users can disable them, or certain browsers might not support them. In such scenarios, alternatives like URL Rewriting and Hidden Fields are used to manage session tracking. Let’s explore these two techniques in detail.

1. URL Rewriting

URL Rewriting is a technique where the session information (usually the session ID) is appended to the URL of every link or form action in the web application. This way, the session ID is carried in the URL, ensuring that it is passed from the client to the server with each request, even if cookies are disabled.

How URL Rewriting Works

When a session is created, the server generates a unique session ID for each user. Instead of relying on cookies to carry this session ID, URL rewriting explicitly appends the session ID to every URL as a query parameter. For example:

- Original URL: http://example.com/page.jsp

- Rewritten URL: http://example.com/page.jsp;jsessionid=12345ABCDEF

The session ID (jsessionid=12345ABCDEF) is appended to the URL. The web server or servlet container recognizes the session ID in the URL and associates it with the correct session object.

URL Encoding in Java Servlets

To encode URLs with the session ID automatically, you can use the encodeURL() method provided by the HttpServletResponse class in Java servlets. This method checks whether the client supports cookies and, if not, adds the session ID to the URL.

Example code:

String encodedURL = response.encodeURL("page.jsp");

- If cookies are enabled, the encoded URL remains as page.jsp.

- If cookies are disabled, the URL will be rewritten to something like page.jsp;jsessionid=12345ABCDEF.

The encodeURL() method ensures that the session ID is included only when necessary.

Advantages of URL Rewriting

- Works even if cookies are disabled: Since the session ID is carried directly in the URL, it doesn’t rely on cookies.

- Simple to implement: Most servlet containers handle URL rewriting automatically when you use encodeURL().

Disadvantages of URL Rewriting

- URL visibility: The session ID is visible in the URL, which could be a security risk if the URL is shared.

- Manual intervention: If the web page has many links, each link must be rewritten with the session ID, which can be error-prone.

- Session expiration: Once the browser is closed, the session ID may be lost if not managed properly.

2. Hidden Fields

Hidden Fields are another way to manage session tracking by storing the session ID in a form’s hidden input field. Hidden fields allow data to be passed from the client to the server without displaying it to the user.

How Hidden Fields Work

The hidden field is added to the HTML form, and when the form is submitted, the session ID is sent to the server as part of the request. Here is an example of an HTML form with a hidden field:

<form action="page.jsp" method="post">
<input type="hidden" name="JSESSIONID" value="<%= session.getId() %>">
<input type="text" name="username" placeholder="Enter Username">
<input type="submit" value="Submit">
</form>

In this example:

- The hidden field (<input type=”hidden” name=”JSESSIONID” value=”<%= session.getId() %>”>) holds the session ID.

- When the form is submitted, the session ID is sent to the server along with the other form data.

The server can then use the session ID from the hidden field to retrieve the session object associated with the user.

Advantages of Hidden Fields

- Compatible with all browsers: Since hidden fields are part of the HTML form, they work with all browsers and are not affected by cookie settings.

- Easy to use with form submissions: Hidden fields integrate seamlessly with form-based interactions in web applications.

Disadvantages of Hidden Fields

- Limited to form submissions: Hidden fields only work when the data is sent via form submissions, making them unsuitable for links or navigation between pages.

- Manual updates required: You need to ensure that the hidden field is included in every form, which can be cumbersome for large applications.

- Security risks: Although hidden fields are not visible to the user, they can still be viewed or modified using browser developer tools, so they are not completely secure.

Comparison of URL Rewriting and Hidden Fields

When to Use URL Rewriting or Hidden Fields

- URL Rewriting:

- Use it when you need to track sessions across multiple pages using links.

- It is more flexible since it works with any type of HTTP request.

- Hidden Fields:

- Use it primarily for form-based interactions.

- It is ideal when you do not want the session ID to appear in the URL.

Combining Techniques for Session Management

For robust session management, it is common to use a combination of cookies, URL rewriting, and hidden fields. Here’s a strategy:

1. Default to Cookies: Use cookies as the primary method for session tracking since they are simple and widely supported.

2. Fallback to URL Rewriting: If cookies are disabled, use URL rewriting to carry the session ID in the URL.

3. Use Hidden Fields: For form submissions, use hidden fields to ensure the session ID is always included in the request.

By combining these techniques, you can ensure that your web application can maintain sessions effectively even if cookies are not supported or are disabled by the user.

Conclusion

URL Rewriting and Hidden Fields are essential alternatives for session tracking when cookies cannot be used. Both techniques have their own use cases and limitations, and understanding their advantages and disadvantages allows you to design more flexible and robust web applications.

Filters in Java Servlets

Filters are web components similar to servlets but designed to perform tasks before and after the core request processing by a servlet. They allow for pre-processing (before request handling) and post-processing (after response handling) of HTTP requests and responses.

Why Use Filters?

Instead of writing the same code for logging, security checks, or other common tasks in multiple servlets, you can use filters to centralize these tasks. This approach reduces code duplication and simplifies maintenance.

Common Tasks Using Filters

- Pre-processing tasks (before core request processing):

- Logging: Keeping track of incoming requests for debugging or auditing.

- Security checks: Implementing authentication and authorization checks to secure resources.

- Session validation: Ensuring that user sessions are valid before allowing access to certain parts of the application.

- Post-processing tasks (after core request processing):

- Data compression: Compressing the response to improve network efficiency.

- Data encoding/encryption: Securing sensitive data in the response.

- URL Rewriting: Modifying URLs in the response, if needed.

Developing Filters with Servlet 2.x

To create a filter using Servlet 2.x, you need to:

1. Create a Filter Class: Implement the javax.servlet.Filter interface.

2. Override Filter Methods: Implement three lifecycle methods:

- init(FilterConfig fc): Initializes the filter.

- doFilter(ServletRequest req, ServletResponse res, FilterChain chain): Handles the request and response.

- destroy(): Releases resources when the filter is destroyed.

3. Configure the Filter in web.xml: Register the filter in the web.xml deployment descriptor.

Example Configuration (web.xml):

<filter>
<filter-name>demoFilter</filter-name>
<filter-class>com.lmsindia.servlet.DemoFilter</filter-class>
<init-param>
<param-name>city</param-name>
<param-value>Noida</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>demoFilter</filter-name>
<url-pattern>/test</url-pattern>
</filter-mapping>

Developing Filters with Servlet 3.0 Annotations

Servlet 3.0 introduced annotations, making it easier to configure filters directly in the Java code without modifying the web.xml file.

Steps to develop a filter using Servlet 3.0:

1. Create a Filter Class: Implement the javax.servlet.Filter interface.

2. Use Annotations: Configure the filter with the @WebFilter annotation.

Example Using Annotations:

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
@WebFilter(filterName="demoFilter", urlPatterns={"/demo.lms"},
initParams={@WebInitParam(name="city", value="Noida")})
public class DemoFilter implements Filter {
@Override
public void init(FilterConfig config) throws ServletException {
System.out.println("**DemoFilter..Init()");
String city = config.getInitParameter("city");
System.out.println(city);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
String name = req.getParameter("name");
String email = req.getParameter("email");
String ip = req.getRemoteAddr();
System.out.println(name);
System.out.println(email);
System.out.println(ip);
chain.doFilter(req, res); // Continue with the next filter or servlet in the chain
System.out.println("DemoFilter doFilter()-after");
}
@Override
public void destroy() {
System.out.println("destroy()");
}
}

Lifecycle of a Filter

1. Initialization: During server startup, filters are initialized with the init() method.

- The container loads the filter class and creates an instance.

- It creates a FilterConfig object containing initialization parameters and a reference to the ServletContext.

- The init() method is called with the FilterConfig object.

2. Request Processing:

- The doFilter() method is invoked for each incoming request.

- It performs pre-processing tasks and then forwards the request to the next filter or the target servlet using chain.doFilter().

- Post-processing tasks are performed after the servlet processes the request.

3. Destruction: When the server shuts down, the filter’s destroy() method is called to release any resources.

Filter Configuration Options

Filters can be configured to apply to multiple servlets in different ways:

1. Mapping by URL pattern:

<filter-mapping>
<filter-name>filterC</filter-name>
<url-pattern>/add.lms</url-pattern>
</filter-mapping>

2. Mapping by servlet name:

<filter-mapping>
<filter-name>lmsSessionFilter</filter-name>
<servlet-name>removeServlet</servlet-name>
</filter-mapping>

3. Mapping to multiple URLs:

<filter-mapping>
<filter-name>filterC</filter-name>
<url-pattern>/add.lms</url-pattern>
<url-pattern>/remove.lms</url-pattern>
</filter-mapping>

4. Mapping to URL patterns with wildcards:

<filter-mapping>
<filter-name>lmsSessionFilter</filter-name>
<url-pattern>*.lms</url-pattern>
</filter-mapping>

Example Files for the Filter Program

1. Index.html: HTML form for user input.

2. DemoServlet.java: Servlet handling the core request processing.

3. DemoFilter.java: Filter for pre-processing and post-processing tasks.

4. web.xml: Servlet configuration file (if not using annotations).

Conclusion

Filters are a powerful way to manage request processing in web applications, allowing developers to handle cross-cutting concerns like security, logging, and data manipulation in a centralized and efficient manner. They help reduce code duplication and make maintenance easier by keeping the logic separate from the core servlet processing.

Explanation of Listener Concepts in Servlet API

Listeners in the Servlet API are a powerful mechanism that allows developers to monitor and respond to specific events in a web application’s lifecycle. They can track various changes in the application, such as the creation or destruction of objects like ServletContext, HttpSession, or request attributes. Here’s a detailed explanation of listeners and their usage:

1. Core Tasks Monitored by Listeners

When a web application is running within a web container, the following tasks can be monitored using listeners:

1. ServletContext Events:

- Creating and destroying the ServletContext object.

- Adding, removing, or replacing attributes in the ServletContext.

2. HttpServletRequest Events:

- Creating and destroying the HttpServletRequest object.

- Adding, removing, or replacing attributes in the HttpServletRequest.

3. HttpSession Events:

- Creating and destroying the HttpSession object.

- Adding, removing, or replacing attributes in the HttpSession.

- Passivating (serializing) and activating (deserializing) the HttpSession.

2. List of Listener Interfaces in the Servlet API

The Servlet API provides several listener interfaces to handle these events. Each listener interface is paired with an event class that encapsulates the event information. Here are the commonly used listener interfaces:

3. Steps to Create a Listener in Servlet 2.x

1. Create a Listener Class: Write your own listener class by implementing the required listener interface.

2. Override the Listener Methods: Implement the methods defined in the listener interface.

Example:

public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// Code to execute when the context is initialized
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Code to execute when the context is destroyed
}
}

3. Register the Listener in web.xml:

<listener>
<listener-class>com.lms.MyListener</listener-class>
</listener>

4. Steps to Create a Listener in Servlet 3.0

1. Create a Listener Class: Implement the listener interface.

2. Override the Listener Methods.

3. Use Annotations to Register: Register the listener using the @WebListener annotation, eliminating the need to modify web.xml.

Example:

@WebListener
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// Code to execute when the context is initialized
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Code to execute when the context is destroyed
}
}

5. Container Tasks During Start-Up and Shutdown

At Start-Up:

1. The ServletContext object is created.

2. Context parameters are retrieved from web.xml and stored.

3. A ServletContextEvent is created.

4. The ServletContextListener is created, and the contextInitialized() method is called.

At Shutdown:

1. The contextDestroyed() method is invoked on the ServletContextListener.

2. The ServletContext object is destroyed.

Program Files Example Overview

1. index.html

This file is the front-end of the web application. It is an HTML file that contains a simple form with a text field for the user to enter their email address and a submit button.

Explanation:

- When the user fills in the email address and clicks on the “Submit” button, the form data is sent to the TestServlet using a POST request.

- The action=”test.lms” in the form specifies that the request should be handled by the servlet mapped to /test.lms.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>lms</h1>
<h2>Listener Example</h2>
<form action="test.lms" method="post">
Enter Email:<input type="text" name="email">
<br/>
<input type="submit" value="submit">
</form>
</body>
</html>

2. TestServlet.java

This is the servlet that processes the form submission from index.html. It interacts with the HttpSession and ServletContext to add, replace, and remove attributes.

Explanation:

- The servlet uses the service() method to handle the HTTP request.

- It retrieves the email parameter from the form and stores it as an attribute in the ServletContext.

- The servlet then performs operations like replacing and removing the attribute from the ServletContext.

- It also invalidates the current session to trigger the session destruction event.

package com.lmsindia.Servlet;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
System.out.println("TestServlet-> service()");
System.out.println("Accessing Session object");
HttpSession session = req.getSession();
String eml = req.getParameter("email");
ServletContext ctx = getServletContext();
System.out.println("Storing attribute in Context");
ctx.setAttribute("email", eml);
System.out.println("Replacing attributes in Context");
ctx.setAttribute("email", "som@lms.com");
System.out.println("Removing attribute in Context");
ctx.removeAttribute("email");
System.out.println("Validating Session Objects");
session.invalidate();
Writer out = res.getWriter();
out.write("<h1>Verify the server console</h1>");
}
}

3. MyContextListener.java

This listener class implements ServletContextListener and listens to the creation and destruction events of the ServletContext.

Explanation:

- contextInitialized() method: Executes when the ServletContext is initialized at the start-up of the web application.

- contextDestroyed() method: Executes when the ServletContext is destroyed during the shutdown of the web application.

package com.lmsindia.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyContextListener implements ServletContextListener {
public MyContextListener() {
System.out.println("** MyContextListener() default constructor");
}
@Override
public void contextDestroyed(ServletContextEvent event) {
ServletContext ctx = event.getServletContext();
System.out.println("ContextDestroyed: " + ctx);
}
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext ctx = event.getServletContext();
System.out.println("ContextInitialized: " + ctx);
}
}

4. MyContextAttributeListener.java

This listener handles changes in attributes within the ServletContext. It implements ServletContextAttributeListener.

Explanation:

- attributeAdded(), attributeRemoved(), and attributeReplaced() methods handle the events of adding, removing, and replacing attributes in the ServletContext.

package com.lmsindia.Servlet;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
public class MyContextAttributeListener implements ServletContextAttributeListener {
public MyContextAttributeListener() {
System.out.println("** MyContextAttributeListener() default constructor");
}
@Override
public void attributeAdded(ServletContextAttributeEvent event) {
String name = event.getName();
String value = event.getValue().toString();
System.out.println("Attribute Added: " + name + "\t" + value);
}
@Override
public void attributeRemoved(ServletContextAttributeEvent event) {
String name = event.getName();
String value = event.getValue().toString();
System.out.println("Attribute Removed: " + name + "\t" + value);
}
@Override
public void attributeReplaced(ServletContextAttributeEvent event) {
String name = event.getName();
String value = event.getValue().toString();
System.out.println("Attribute Replaced: " + name + "\t" + value);
}
}

5. MySessionListener.java

This listener monitors session events. It implements HttpSessionListener.

Explanation:

- sessionCreated() method: Executes when a new session is created.

- sessionDestroyed() method: Executes when a session is destroyed.

package com.lmsindia.Servlet;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
public MySessionListener() {
System.out.println("** MySessionListener() default constructor");
}
@Override
public void sessionCreated(HttpSessionEvent event) {
System.out.println("Session Created");
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
System.out.println("Session Destroyed");
}
}

6. MyRequestListener.java

This listener tracks the creation and destruction of HTTP requests. It implements ServletRequestListener.

Explanation:

- requestInitialized() method: Executes when a request is initialized.

- requestDestroyed() method: Executes when a request is destroyed.

package com.lmsindia.Servlet;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class MyRequestListener implements ServletRequestListener {
public MyRequestListener() {
System.out.println("MyRequestListener() default constructor");
}
@Override
public void requestDestroyed(ServletRequestEvent event) {
System.out.println("Request Destroyed");
}
@Override
public void requestInitialized(ServletRequestEvent event) {
System.out.println("Request Initialized");
}
}

7. web.xml

This is the deployment descriptor file that configures the servlet and listener classes for the web application. It tells the web container which classes to use for handling specific events.

Explanation:

- It defines servlet mappings for TestServlet.

- It registers all the listeners (MyContextListener, MyContextAttributeListener, MyRequestListener, and MySessionListener).

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>lms27</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.lmsindia.Servlet.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/test.lms</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.lmsindia.Servlet.MyContextListener</listener-class>
</listener>
<listener>
<listener-class>com.lmsindia.Servlet.MyContextAttributeListener</listener-class>
</listener>
<listener>
<listener-class>com.lmsindia.Servlet.MyRequestListener</listener-class>
</listener>
<listener>
<listener-class>com.lmsindia.Servlet.MySessionListener</listener-class>
</listener>
</web-app>

Summary

- index.html: Displays the form for user input.

- TestServlet.java: Processes the form submission and interacts with context and session attributes.

- Listener classes (MyContextListener, MyContextAttributeListener, MySessionListener, MyRequestListener): Handle various lifecycle events of the web application’s components.

- web.xml: Configures the servlet and listeners to handle requests and lifecycle events.

These files work together to demonstrate how listeners can be used to track and respond to different events in a Java web application’s lifecycle.

Here are the key components of a sample Servlet listener implementation:

1. HTML Form (index.html): Contains a simple form for user interaction.

2. TestServlet.java: Implements the core logic to interact with session and context attributes.

3. Listener Classes:

- MyContextListener.java: Tracks ServletContext initialization and destruction.

- MyContextAttributeListener.java: Tracks attribute changes in the ServletContext.

- MySessionListener.java: Monitors session creation and destruction.

- MyRequestListener.java: Monitors request creation and destruction.

4. Web Configuration (web.xml): Registers servlets and listeners to the application.

This approach helps you efficiently manage the different states of your web application’s objects while keeping the code modular and maintainable.

Session Migration

What is Session Migration?

Session migration is the process of transferring a user’s session data from one server to another in a distributed or clustered server environment. This is common in large-scale enterprise applications where multiple servers (nodes) are used to handle numerous user requests efficiently.

Why Session Migration is Needed?

In a clustered environment, load balancers distribute user requests across multiple servers to handle the load efficiently. If a user starts a session on one server and then their next request is handled by a different server, the session data must be migrated to maintain continuity.

How Session Migration Works:

- Session Creation: The user’s first request is processed by a server (e.g., Server 1), where a session object is created.

- Session Migration: If the subsequent request from the same user is handled by a different server (e.g., Server 3), the session object must be transferred from Server 1 to Server 3.

- Events in Session Migration: Two key events occur during session migration:

- Session Passivation: The session is passivated (temporarily stored or serialized) on Server 1 before being transferred.

- Session Activation: The session is activated (restored or deserialized) on Server 3 when it is needed.

Handling Session Events with HttpSessionActivationListener

To handle session passivation and activation events, you can use the HttpSessionActivationListener interface with the following methods:

- void sessionWillPassivate(HttpSessionEvent event): This method is called by the web container when the session is about to be passivated on the original server (e.g., Server 1).

- void sessionDidActivate(HttpSessionEvent event): This method is called by the web container when the session is activated on the new server (e.g., Server 3).

Servlet API and Class Hierarchy

Overview of the Servlet API:

- javax.servlet.Servlet Interface: This is the root interface for all servlets. It defines the service() method, which is responsible for handling requests from the client.

- javax.servlet.GenericServlet Class: This is an abstract class that implements the Servlet interface. It provides default implementations for some methods and leaves the service() method abstract. It is used as a base class for servlets that are not tied to any specific protocol.

- javax.servlet.http.HttpServlet Class: This class extends GenericServlet and is designed for HTTP-based servlets. It provides methods for handling HTTP-specific request types like GET, POST, PUT, and others.

Servlet Class Hierarchy:

1. Servlet Interface

- Contains the method: void service(ServletRequest req, ServletResponse res)

2. GenericServlet Class

- Extends the Servlet interface and provides a skeletal implementation.

- The service() method remains abstract in this class.

3. HttpServlet Class

- Extends GenericServlet.

- It provides implementations for HTTP-specific methods like doGet(), doPost(), and others.

3. Servlet Method Overriding Cases

Case 1: Extending HttpServlet and Overriding the Generic service() Method

If you extend HttpServlet and override the generic service() method, then that overridden method will be called for every request, regardless of the HTTP method (GET, POST, etc.).

class HelloServlet extends HttpServlet {
@Override
public void service(ServletRequest req, ServletResponse res) {
// This method will handle all incoming HTTP requests.
}
}

Case 2: Extending HttpServlet and Overriding the HTTP service() Method

In this scenario, you extend HttpServlet and override the HTTP-specific service() method, which handles incoming requests at the HTTP level. This method internally determines the HTTP method (GET, POST, etc.) and calls the appropriate doXXX() method.

class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) {
// This method will handle all HTTP requests and delegate to doGet(), doPost(), etc.
}
}

Case 3: Extending GenericServlet and Overriding the service() Method

If you extend GenericServlet directly and override the service() method, you will handle all incoming requests generically, without any protocol-specific logic (like GET or POST).

class HelloServlet extends GenericServlet {
@Override
public void service(ServletRequest req, ServletResponse res) {
// Handles all requests as a generic servlet, not HTTP-specific.
}
}

Explanation:

- Extending GenericServlet means that your servlet is protocol-independent.

- Since you’re not tied to HTTP, you can’t use methods like doGet() or doPost().

Case 4: Extending HttpServlet and Overriding Both service() Methods

If you override both the generic service() method and the HTTP-specific service() method in HttpServlet, then both methods play different roles:

- The generic service() method will handle all incoming requests.

- The HTTP service() method will delegate to the appropriate doXXX() method based on the HTTP request type.

class HelloServlet extends HttpServlet {
@Override
public void service(ServletRequest req, ServletResponse res) {
// Generic service method
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) {
// HTTP-specific service method
}
}

Explanation:

- The container first calls the generic service() method, which might call the HTTP-specific service() method.

- The HTTP-specific method then delegates to doGet(), doPost(), etc., depending on the request type.

Case 5: Extending HttpServlet and Overriding the doGet() Method

When you extend HttpServlet and only override the doGet() method, the container automatically determines which HTTP method is being requested and calls the appropriate doXXX() method.

class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// Handle GET request
}
}

Explanation:

- The container invokes the HTTP service() method of HttpServlet.

- The service() method checks the HTTP method of the request and calls doGet(), doPost(), or other doXXX() methods.

Key Points to Remember:

- Generic service() Method: If you override this method in your servlet, it will handle all incoming requests regardless of the HTTP method.

- HTTP service() Method: If you override this method, it can delegate to HTTP-specific methods like doGet() or doPost().

- doXXX() Methods: These methods (doGet(), doPost(), etc.) are specifically designed to handle HTTP requests based on the method type. Overriding these methods allows you to handle requests in a more structured and organized way.

HTTP Status Code 405 Error

- HTTP Status 405: This error indicates that the HTTP method (e.g., POST) is not supported by the requested URL. This happens when you try to handle a request with a method that your servlet does not support or has not overridden.

Understanding these cases helps you write more efficient and robust servlets, taking advantage of the servlet lifecycle and session management features to handle HTTP requests properly in your web applications.

--

--

Pratik T
Pratik T

Written by Pratik T

Full Stack Developer skilled in Machine Learning, Deep Learning, Computer Vision, and NLP. Committed to making learning accessible to all.