Skip to content

Servlets

🔹 What is a Servlet?

  • A Servlet is a Java class used to extend the capabilities of servers that host applications accessed by means of a request-response programming model.
  • Primarily, servlets are used to create web applications that run on a server.
  • They handle HTTP requests and responses, processing client requests (like from browsers) and generating dynamic content (like HTML).

🔹 Key Features of Servlets

  • Server-side Java programs.
  • Platform-independent.
  • Efficient and scalable.
  • Can handle multiple requests concurrently using multithreading.
  • Part of Java EE (Enterprise Edition) but can run in servlet containers like Apache Tomcat, Jetty.

🔹 How Servlets Work (Lifecycle)

  1. Servlet class loaded by server.
  2. Servlet instance created.
  3. init() method called once to initialize servlet.
  4. For each client request:

  5. service() method called — it processes the request.

  6. Inside service(), depending on HTTP method, doGet(), doPost(), etc. methods are called.
  7. When server stops or servlet is no longer needed:

  8. destroy() method called to clean up resources.


🔹 Servlet API Basics

Servlets extend the class:

javax.servlet.http.HttpServlet

Key methods you override:

Method Purpose
init() Initialization when servlet loads
doGet() Handles HTTP GET requests
doPost() Handles HTTP POST requests
destroy() Cleanup before servlet is removed

🔹 Simple Servlet Example

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        // Set response content type
        response.setContentType("text/html");

        // Write response
        PrintWriter out = response.getWriter();
        out.println("<h1>Hello from Servlet!</h1>");
    }
}

🔹 How to Deploy a Servlet?

  • Servlets run inside a Servlet container (like Apache Tomcat).
  • You package your servlet in a WAR (Web Application Archive) file.
  • The deployment descriptor web.xml (in WEB-INF folder) defines servlet mappings.

Example web.xml snippet:

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

🔹 Advantages of Servlets

  • Portable and platform-independent.
  • Faster than CGI scripts (because they run inside JVM and are multithreaded).
  • Can maintain session information.
  • Integration with Java technologies (JSP, JDBC, etc.).

🔹 Summary

Aspect Description
Purpose Server-side Java program for handling requests
Runs on Servlet container (Tomcat, Jetty, etc.)
Lifecycle Methods init(), service(), doGet(), doPost(), destroy()
Handles HTTP requests and responses
Used for Dynamic web content generation

Environment and Roles in Servlets

🔹 Servlet Environment

The servlet environment refers to the entire runtime setup required for servlets to execute and handle client-server communication. This includes:

1. Web Server / Servlet Container

  • A web server or more accurately, a servlet container (like Apache Tomcat, Jetty, or GlassFish) provides the runtime environment for servlets.
  • It:

  • Loads servlet classes.

  • Manages servlet lifecycle.
  • Listens to HTTP requests and routes them to the appropriate servlet.
  • Provides interfaces like HttpServletRequest, HttpServletResponse, etc.

2. Servlet API

  • Provided by Java EE or Jakarta EE, includes:

  • javax.servlet.*

  • javax.servlet.http.*
  • Defines interfaces and classes that allow servlet communication with the server and client (browser).

3. Deployment Descriptor (web.xml)

  • Configuration file located at: WEB-INF/web.xml
  • Specifies servlet names, classes, and URL mappings.

🔹 Roles in Servlet Architecture

Servlet-based web applications usually involve three main roles:

1. Client

  • Usually a web browser.
  • Sends HTTP requests (GET, POST) to the server.
  • Receives HTTP responses (HTML, JSON, etc.).

2. Web Server / Servlet Container

  • Middleman between client and servlet.
  • Responsibilities:

  • Manage servlet lifecycle.

  • Map requests to appropriate servlet based on URL.
  • Handle multi-threading and resource sharing.
  • Provide session management and security.

3. Servlet (Web Component)

  • Java class written by the developer.
  • Handles business logic.
  • Interacts with:

  • Clients (via HttpServletRequest and HttpServletResponse).

  • Databases (via JDBC).
  • Other services (APIs, files, etc.).
  • Generates dynamic responses like HTML or JSON.

🔹 Additional Roles in Enterprise Setup

Role Description
Developer Writes servlets and web components using Java Servlet API.
System Admin Configures the server, deploys web applications, manages WAR files.
Servlet Container Executes servlet code, manages threads, memory, and connections.
Database Often used with servlets via JDBC to store or retrieve data.

🔹 Real-World Analogy

Component Real-World Equivalent
Client Customer placing an order
Servlet Container Waiter who takes and processes the order
Servlet Chef who prepares the food
Database Kitchen storage or inventory

🔹 Summary Table

Environment Component Role
Servlet API Java classes & interfaces for servlet development
Servlet Container Runs servlets, handles requests/responses, manages lifecycle
Client (Browser) Sends request, receives response
web.xml / annotations Maps URLs to servlets, defines configuration
JDBC / DB Connection Enables data storage and retrieval

Architectural Role of Servlets

🔷 What is the Architectural Role of Servlets?

In the architecture of Java-based web applications, Servlets play the central role as the controller component in a client-server model. Servlets sit between the client (browser) and the backend resources (like databases, business logic, etc.).


🔷 Servlets in MVC Architecture

Servlets are often part of the MVC (Model-View-Controller) design pattern:

1. Model

  • Handles the business logic and data.
  • Usually consists of Java classes and interacts with a database (via JDBC).

2. View

  • Represents the presentation layer.
  • Usually implemented using JSP (JavaServer Pages) or HTML/CSS.
  • Displays data to the user.

3. Controller (Servlet)

  • Servlets act as Controllers.
  • Receive HTTP requests from clients.
  • Process the request (including calling model logic).
  • Forward the result to the View (JSP or HTML page).

Diagram:

Client (Browser)
       ↓
HTTP Request
       ↓
Servlet (Controller)
       ↓
Business Logic / DB (Model)
       ↓
Forward to JSP (View)
       ↓
HTTP Response
       ↓
Client

🔷 Servlet’s Role in Web Application Architecture

1. Request Processing

  • Servlets handle incoming HTTP GET/POST requests.
  • Extract data from requests (e.g., form fields, URL parameters).

2. Routing and Logic

  • Decide what logic to execute based on the request (like user login, registration, etc.).
  • Call appropriate Java classes or services (business logic).

3. Response Generation

  • Servlets either:

  • Generate response directly (e.g., HTML using PrintWriter), OR

  • Forward request to JSP for rendering the response.

4. Session Management

  • Servlets can manage user sessions using HttpSession objects (like shopping cart or login state).

5. Security Handling

  • Can control access to certain resources using authentication and authorization.

🔷 Example Flow (User Login)

  1. User submits login form (login.html).
  2. Servlet /LoginServlet receives the form data.
  3. Servlet validates credentials by calling the UserDAO (Model).
  4. If valid:

  5. Store user info in session.

  6. Forward to welcome.jsp.
  7. If invalid:

  8. Redirect to error.jsp.


🔷 Servlet Interaction Summary

Role Description
Request Receiver Accepts HTTP requests from clients (browsers)
Dispatcher Determines action based on input (e.g., route or command)
Business Invoker Calls business logic classes
View Forwarder Forwards control to JSP or other view components
Session Manager Manages login states, shopping carts, etc.
Error Handler Catches and redirects on error

🔷 Advantages of Using Servlets in Architecture

  • Efficient and Scalable: Multithreaded by default.
  • Reusable and Maintainable: Follows modular structure.
  • Secure: Can manage sessions and access control.
  • Flexible: Integrates with databases, services, APIs, etc.

🔷 Summary

Component Role of Servlet
Client Sends request to servlet
Servlet Controls flow, processes logic, manages sessions
Model (Java Class + JDBC) Performs business logic and DB operations
View (JSP/HTML) Displays data to the user

HTML Support

🔷 HTML Support in Servlets

Although Servlets are Java classes, they generate and support HTML to interact with users through a web browser. This means a servlet can dynamically create HTML pages (or fragments) in response to client requests.


🔹 Why HTML Support is Important

  • Web browsers only understand HTML, CSS, and JavaScript.
  • Servlets provide a bridge between the server-side logic (Java) and the client-side UI (HTML).
  • They generate dynamic HTML based on business logic, user input, or data from a database.

🔹 How Servlets Generate HTML

In servlets, HTML content is written using a PrintWriter object obtained from the HttpServletResponse.

✅ Example: Basic HTML Generation in Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HtmlSupportServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        // Set response content type
        response.setContentType("text/html");

        // Get the output stream
        PrintWriter out = response.getWriter();

        // Write HTML content
        out.println("<html>");
        out.println("<head><title>HTML in Servlet</title></head>");
        out.println("<body>");
        out.println("<h1>Welcome to Servlet HTML Support</h1>");
        out.println("<p>This is a dynamic web page generated using Servlet and HTML.</p>");
        out.println("</body></html>");
    }
}

🔹 Key Points When Using HTML in Servlets

Feature Explanation
contentType Should be set to "text/html" using setContentType()
PrintWriter Used to send HTML content to the browser
String Concatenation HTML is often written as string literals
Dynamic Content HTML elements can be generated conditionally or with loops

🔹 Dynamic HTML with Data

Servlets can generate HTML that includes dynamic data, for example:

String user = request.getParameter("username");
out.println("<h2>Welcome, " + user + "!</h2>");

This personalizes the page based on user input.


🔹 Limitations

  • Writing large HTML code in servlets is messy and hard to maintain.
  • This is why JSP (JavaServer Pages) is often used to separate Java logic and HTML presentation.

🔹 Best Practices

  • Use Servlets for control and logic, not for complex HTML design.
  • Use JSP or templates to handle presentation (HTML).
  • Keep servlet HTML output minimal or delegate to JSP using RequestDispatcher.

🔹 Summary

Aspect Details
Output Format text/html
Output Tool PrintWriter
HTML Usage Directly written inside out.println()
Good For Dynamic HTML generation
Not Ideal For Large/complex HTML (use JSP instead)

Generation

🔷 Generation in Java Servlet Context

In the context of Java Servlets, generation typically refers to the dynamic generation of content, especially HTML output that is sent back to the user's browser. Let's explore this concept in detail.


🔹 What is Content Generation?

Content generation means that the server (Servlet) dynamically creates web content (HTML, JSON, XML, etc.) based on logic, user input, or database results.

Instead of serving a static HTML file, servlets generate the content on-the-fly each time a client sends a request.


🔹 Types of Content that Can Be Generated

  1. HTML Web Pages (most common)
  2. JSON (for APIs)
  3. XML (used in data exchange)
  4. File Downloads (like PDFs or Excel)
  5. Images (in some advanced use cases)

🔹 Example: HTML Generation

Here's how a servlet generates HTML:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");         // Set response type
    PrintWriter out = response.getWriter();       // Get writer to send output

    // Generate HTML content
    out.println("<html>");
    out.println("<head><title>Generated Page</title></head>");
    out.println("<body>");
    out.println("<h1>Hello, this page was generated dynamically!</h1>");
    out.println("</body></html>");
}

The browser receives this as if it were a normal HTML file.


🔹 Dynamic Generation Based on User Input

Servlets can use user input to dynamically generate different outputs:

String name = request.getParameter("username");

out.println("<h2>Hello, " + name + "!</h2>");

🔹 Generation from Database

Servlets can generate HTML based on database data:

ResultSet rs = stmt.executeQuery("SELECT * FROM students");

while(rs.next()) {
    out.println("<p>" + rs.getString("name") + "</p>");
}

This means every user could see different content based on what's stored in the database.


🔹 Summary Table

Aspect Description
Definition Creating content on-the-fly inside servlet
Output Format HTML, JSON, XML, etc.
Tools Used PrintWriter, HttpServletResponse, ResultSet, etc.
Source of Data User input, backend logic, database
Common Usage Dynamic web pages, personalized greetings, reports

🔹 When is Generation Useful?

  • Login pages showing user-specific content
  • Reports pulled from databases
  • Real-time dashboards
  • Search results
  • API responses

Server Side

🔷 Server-Side in Java Programming

Server-side refers to the part of a web application that runs on the server—not on the user's browser (client-side). In Java, server-side programming is typically done using Servlets, JSP, and Java EE components to handle business logic, database interaction, session management, and more.


🔹 What is Server-Side?

  • Executes on the web server (like Apache Tomcat, Jetty, etc.).
  • Handles HTTP requests from the client (browser).
  • Processes logic like:

  • Authenticating users

  • Storing or retrieving data from a database
  • Generating dynamic content
  • Sends back HTTP responses (usually HTML, JSON, or files).

🔹 Java Technologies for Server-Side Programming

Technology Description
Servlets Java classes that handle HTTP requests and generate responses.
JSP (JavaServer Pages) Simplifies writing HTML that includes Java code.
JDBC Connects Java applications to databases.
EJB (Enterprise JavaBeans) Used in large enterprise applications for business logic.
Spring / Spring Boot Popular modern Java frameworks for building robust server-side apps.

🔹 Servlet as a Server-Side Component

A Java Servlet is a perfect example of a server-side program:

✅ Example

@WebServlet("/greet")
public class GreetingServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        String name = request.getParameter("name");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html><body>");
        out.println("<h2>Hello, " + name + "!</h2>");
        out.println("</body></html>");
    }
}

When a client accesses http://localhost:8080/greet?name=Alice, the servlet (on server-side) runs and returns a customized greeting.


🔹 Server-Side Responsibilities

Function Role in Server-Side
Request Handling Parse incoming data from HTTP requests.
Authentication/Authorization Check if the user is valid or allowed.
Database Operations Read/write from/to a database using JDBC.
Business Logic Execution Execute application-specific operations.
Response Generation Build and return dynamic content (HTML/JSON).
Session Management Track user interactions across multiple requests.

🔹 Difference: Server-Side vs Client-Side

Feature Client-Side Server-Side
Runs On User's browser Web server (e.g., Tomcat)
Languages HTML, CSS, JavaScript Java (Servlet, JSP, etc.)
Access to DB No direct access Full database access via JDBC
Security Level Limited High (handles sensitive logic)
Used For Display, form validation Processing, storage, user auth

🔹 Summary

  • Server-side in Java uses technologies like Servlets, JSP, JDBC, and frameworks.
  • Handles logic, data storage, security, and response creation.
  • It’s where the core of your web application actually runs.
  • Server-side works together with the client-side (HTML/JavaScript) to form a complete web application.

🔷 Installing and Setting Up Servlets in Java

To run Java Servlets, you need a Servlet container (like Apache Tomcat), a Java Development Kit (JDK), and a way to write and compile code (like an IDE or text editor + terminal). Below is a complete guide to install and run Servlets.


🔹 1. Prerequisites

Tool Purpose
JDK Required to compile and run Java code
Apache Tomcat Servlet container to deploy and run servlets
IDE or Editor Write code (Eclipse, IntelliJ, VS Code, or Notepad++)
Web Browser Test your servlet

🔹 2. Download and Install Required Software

✅ Install JDK

java -version
javac -version

✅ Install Apache Tomcat

  • Download from: https://tomcat.apache.org
  • Choose the latest version of Tomcat 9 or 10
  • Extract it to a folder (e.g., C:\Tomcat or /opt/tomcat)

✅ Folder Structure in Tomcat

Important folders:

tomcat/
 └── webapps/      → Web applications go here
     └── YourApp/
         ├── WEB-INF/
         │   ├── web.xml
         │   └── classes/
         │       └── YourServlet.class

🔹 3. Write a Simple Servlet

Create a file HelloServlet.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<h1>Hello from Servlet</h1>");
    }
}

🔹 4. Create Directory Structure

MyApp/
 ├── index.html
 └── WEB-INF/
     ├── web.xml
     └── classes/
         └── HelloServlet.class

✅ web.xml (Servlet Configuration)

<web-app>
  <servlet>
    <servlet-name>Hello</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>

🔹 5. Compile the Servlet

javac -classpath /path/to/tomcat/lib/servlet-api.jar HelloServlet.java

Replace /path/to/tomcat with the actual path to your Tomcat folder.

  • Put the compiled HelloServlet.class in: MyApp/WEB-INF/classes/

🔹 6. Deploy the Servlet

  1. Copy the entire MyApp/ folder to:

/path/to/tomcat/webapps/

  1. Start Tomcat:

  2. Windows: bin/startup.bat

  3. Linux/Mac: bin/startup.sh

🔹 7. Access the Servlet

Open a browser and visit:

http://localhost:8080/MyApp/hello

You should see:

Hello from Servlet

🔹 8. Use an IDE (Optional)

You can simplify the process by using an IDE like:

  • Eclipse IDE for Enterprise Java

  • Create a Dynamic Web Project

  • Write Servlet
  • Deploy to embedded Tomcat
  • IntelliJ IDEA

  • Use “Java Enterprise” and configure Tomcat

  • Supports hot deployment and integrated server

🔹 Summary

Step Action
Install JDK Compile Java code
Install Tomcat Run Servlet container
Write Servlet Java class extending HttpServlet
Setup web.xml Configure servlet mapping
Compile Servlet Use servlet-api.jar from Tomcat
Deploy to Tomcat Place your app in webapps/ folder
Run Access via browser at http://localhost:8080/...

🔷 Servlet API in Java

The Servlet API is a set of Java classes and interfaces provided by Java EE (Jakarta EE) that allows developers to write server-side programs called Servlets. These servlets respond to client requests—usually over HTTP—in web applications.


🔹 What is the Servlet API?

  • The Servlet API provides the foundation for developing servlets.
  • It defines interfaces, classes, and methods required to handle:

  • HTTP requests/responses

  • Session tracking
  • Cookies
  • Initialization/configuration of servlets

🔹 Packages in the Servlet API

Package Name Description
javax.servlet Contains core classes and interfaces for generic servlet development.
javax.servlet.http Contains classes specific to HTTP protocol, such as HttpServlet.

Note: In modern Java EE (Jakarta EE), the package is renamed to jakarta.servlet and jakarta.servlet.http.


🔹 Key Interfaces and Classes in Servlet API

✅ 1. Servlet (Interface)

  • The base interface for all servlets.
  • Every servlet class must implement it (usually indirectly via HttpServlet).

✅ 2. GenericServlet (Abstract Class)

  • Implements Servlet and provides basic structure.
  • Suitable for protocol-independent servlets (rarely used directly).

✅ 3. HttpServlet (Abstract Class)

  • The most commonly used base class.
  • Designed for HTTP-specific functionality.
  • Override methods like doGet(), doPost(), etc.

✅ 4. ServletRequest

  • Represents incoming client request.
  • Provides methods like:

java String getParameter(String name); String getRemoteAddr();

✅ 5. ServletResponse

  • Represents the response going back to the client.
  • Provides method:

java PrintWriter getWriter();

✅ 6. HttpServletRequest

  • Extends ServletRequest with HTTP-specific methods like:

java String getHeader(String name); String getMethod();

✅ 7. HttpServletResponse

  • Extends ServletResponse with methods to send HTTP-specific data:

java void sendRedirect(String location); void setStatus(int sc);

✅ 8. ServletConfig

  • Contains initialization parameters for the servlet.
  • Passed by the container during servlet initialization.

✅ 9. ServletContext

  • Represents the entire web application context.
  • Used for application-wide parameters, logging, and resource sharing.

🔹 Common Lifecycle Methods (from Servlet API)

Method Description
init() Called once when the servlet is first loaded.
service() Called for every request (handles both GET and POST).
destroy() Called once before servlet is destroyed.

🔹 Example Code Using Servlet API

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<h1>Hello from Servlet API</h1>");
    }
}

🔹 How to Use the Servlet API in Projects

  1. Make sure your project includes the servlet-api.jar:

  2. In Tomcat: /lib/servlet-api.jar

  3. In Maven:
<dependency>
  <groupId>jakarta.servlet</groupId>
  <artifactId>jakarta.servlet-api</artifactId>
  <version>5.0.0</version>
  <scope>provided</scope>
</dependency>

🔹 Summary Table

Component Role
HttpServlet Base class for HTTP Servlets
HttpServletRequest Access request parameters and headers
HttpServletResponse Write response back to the client
ServletConfig Get servlet-specific config
ServletContext App-wide data sharing and logging
Lifecycle methods init(), service(), destroy()

🔷 Servlet Life Cycle in Java

The Servlet life cycle defines the stages through which a servlet instance passes from creation to destruction. Managed by the Servlet container (like Apache Tomcat), the life cycle ensures the servlet is properly initialized, used to handle requests, and then destroyed.


🔹 Life Cycle Phases

There are three main phases in the servlet life cycle:

Phase Method Description
1. Initialization init() Called once when the servlet is first loaded.
2. Request Handling service() Called every time the servlet receives a client request.
3. Destruction destroy() Called once when the servlet is being removed from memory.

🔹 Servlet Life Cycle Methods in Detail

✅ 1. init(ServletConfig config)

  • Called only once when the servlet is first loaded into memory.
  • Used to perform initial setup (e.g., opening database connections).
  • Provided by the GenericServlet class.
public void init() throws ServletException {
    // Initialization logic here
}

✅ 2. service(ServletRequest request, ServletResponse response)

  • Called every time a request is made.
  • It determines the type of request (GET, POST, etc.).
  • Delegates the request to doGet(), doPost(), etc., in HttpServlet.
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // Handle GET request
}

✅ 3. destroy()

  • Called once when the servlet is being unloaded or shut down.
  • Used to release resources (e.g., closing database connections, file handles).
public void destroy() {
    // Cleanup code
}

🔹 Life Cycle Flow Diagram

Client Requests Servlet → Servlet Container
        |
        ↓
     [Loading Servlet]
        ↓
     init()
        ↓
     service()
        ↓
     service()
        ↓
     ...
        ↓
     destroy()

🔹 Example Servlet with Life Cycle Methods

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LifeCycleServlet extends HttpServlet {

    public void init() {
        System.out.println("Servlet is being initialized");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<h2>Hello from doGet method!</h2>");
    }

    public void destroy() {
        System.out.println("Servlet is being destroyed");
    }
}

🔹 Summary Table

Method Purpose Called When
init() Initialize the servlet Only once when servlet loads
service() Handle each request On every request
doGet() / doPost() Handle HTTP methods Inside service()
destroy() Clean up resources When servlet is unloaded

🔷 HTML to Servlet Communication in Java

HTML to Servlet communication refers to how a client (usually a web browser) sends data to a Java Servlet via an HTML form, and how the servlet receives, processes, and responds to that data.


🔹 How It Works

  1. The HTML form is created with a form tag that sends data to the servlet.
  2. When the user submits the form, the browser sends an HTTP request (GET or POST).
  3. The Servlet receives the request using HttpServletRequest.
  4. It processes the data and optionally returns a response using HttpServletResponse.

🔹 Communication Steps

Step Description
1️⃣ HTML form collects user input.
2️⃣ Form data is sent to a servlet via action attribute.
3️⃣ Servlet reads form data using request.getParameter().
4️⃣ Servlet sends response using response.getWriter().

🔹 Example: HTML Form

<!-- file: login.html -->
<!DOCTYPE html>
<html>
<head><title>Login Form</title></head>
<body>
  <form action="LoginServlet" method="post">
    Username: <input type="text" name="username"><br>
    Password: <input type="password" name="password"><br>
    <input type="submit" value="Login">
  </form>
</body>
</html>
  • action="LoginServlet" means form data will be sent to LoginServlet.
  • method="post" means data will be sent via HTTP POST.

🔹 Example: Java Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {

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

        // Reading form data
        String user = request.getParameter("username");
        String pass = request.getParameter("password");

        // Preparing response
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        if ("admin".equals(user) && "1234".equals(pass)) {
            out.println("<h2>Login Successful!</h2>");
        } else {
            out.println("<h2>Invalid Username or Password</h2>");
        }
    }
}

🔹 Servlet Mapping in web.xml

In traditional servlet-based apps (not using annotations), you must map the servlet:

<web-app>
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>LoginServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
</web-app>

Or use annotations:

@WebServlet("/LoginServlet")

🔹 Summary

Component Role
HTML Form Collects and submits user data
HttpServletRequest Reads submitted data
HttpServletResponse Sends data back to client
Servlet Processes and responds to the request