> For the complete documentation index, see [llms.txt](https://codewithmeiy.gitbook.io/core-java/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://codewithmeiy.gitbook.io/core-java/servlets.md).

# Servlets

Servlets are a fundamental part of Java's web technology stack. They are server-side components that extend the capabilities of web servers and facilitate the creation of dynamic web applications. Servlets process client requests and generate responses, making them a key player in building web applications. In this guide, we'll cover the basics of servlets with suitable examples.

### Prerequisites

Before diving into servlets, ensure that you have the following prerequisites:

1. **Java**: Basic knowledge of Java programming.
2. **Eclipse IDE** (or any Java IDE of your choice).
3. **Apache Tomcat**: A web server or servlet container. Download and install it from the Apache Tomcat website (<https://tomcat.apache.org/>).

### Creating a Simple Servlet

In this section, we'll create a basic servlet and deploy it on the Apache Tomcat server.

1. **Open Eclipse** and create a new dynamic web project:
   * File > New > Dynamic Web Project.
   * Enter a project name, e.g., "SimpleServletDemo."
2. **Create a Servlet Class**:
   * Right-click on the `src` folder within your project.
   * Select New > Servlet.
   * Provide a package name (e.g., `com.example`) and a class name (e.g., `SimpleServlet`).
   * Click Next, then Finish.
3. **Edit the Servlet Class**:

   In the `SimpleServlet.java` class that was generated, override the `doGet` method to handle HTTP GET requests:

   ```java
   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("/SimpleServlet")
   public class SimpleServlet extends HttpServlet {
       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           response.getWriter().println("Hello, World from SimpleServlet!");
       }
   }
   ```
4. **Configure the Deployment Descriptor**:

   * Open the `web.xml` file in the `WEB-INF` folder of your project.
   * Add the following servlet and servlet-mapping entries:

   ```xml
   <servlet>
       <servlet-name>SimpleServlet</servlet-name>
       <servlet-class>com.example.SimpleServlet</servlet-class>
   </servlet>
   <servlet-mapping>
       <servlet-name>SimpleServlet</servlet-name>
       <url-pattern>/SimpleServlet</url-pattern>
   </servlet-mapping>
   ```
5. **Run the Application**:
   * Right-click on your project.
   * Select Run As > Run on Server.
   * Choose the Tomcat server and click Finish.
   * Your servlet will be accessible at `http://localhost:8080/SimpleServletDemo/SimpleServlet`.

### Handling HTTP Requests

Servlets can handle different HTTP methods like GET, POST, and more. Here's how to handle a POST request in a servlet:

```java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Process POST request here
}
```

### Request and Response Objects

Servlets use `HttpServletRequest` and `HttpServletResponse` objects to interact with the client:

* `HttpServletRequest`: Represents the request made by the client and provides methods to access request parameters, headers, and more.
* `HttpServletResponse`: Represents the response that will be sent to the client. You can set response content, headers, and status codes using this object.

### Example: Reading Request Parameters

```java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String name = request.getParameter("name");
    response.getWriter().println("Hello, " + name + "!");
}
```

### Sending Redirects

You can use the `sendRedirect` method to redirect a client to another URL:

```java
response.sendRedirect("newpage.jsp");
```

### Session Management

Servlets can maintain session data using `HttpSession`:

```java
// Create or access a session
HttpSession session = request.getSession();

// Store data in the session
session.setAttribute("username", "john_doe");

// Retrieve data from the session
String username = (String) session.getAttribute("username");
```

Servlets are a powerful tool for building dynamic web applications in Java. They handle HTTP requests and responses, allowing you to create interactive and data-driven web applications. This guide provides a foundational understanding of servlets, and further exploration and practice will enhance your web development skills.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://codewithmeiy.gitbook.io/core-java/servlets.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
