0% found this document useful (0 votes)
4 views22 pages

Advanced Java Technologies - Servlets

This document provides comprehensive notes on Java Servlets, covering their definition, architecture, and the role of web containers like Tomcat. It includes setup instructions for Eclipse and Tomcat, project creation steps, and servlet programming techniques such as handling GET and POST requests, session management, and using annotations for configuration. Additionally, it discusses servlet lifecycle, request/response handling, and best practices for servlet development.

Uploaded by

sohamwagale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views22 pages

Advanced Java Technologies - Servlets

This document provides comprehensive notes on Java Servlets, covering their definition, architecture, and the role of web containers like Tomcat. It includes setup instructions for Eclipse and Tomcat, project creation steps, and servlet programming techniques such as handling GET and POST requests, session management, and using annotations for configuration. Additionally, it discusses servlet lifecycle, request/response handling, and best practices for servlet development.

Uploaded by

sohamwagale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Advanced Java Technologies - Servlets

# Java Servlets - Complete Course Notes

## 1. Introduction to Servlets

### What is a Servlet?


- A **Servlet** is a Java file that can:
- Take requests from clients on the internet
- Process those requests
- Provide responses in HTML format

### Client-Server Architecture

```
Client Machine → Request → Server

Web Container (Tomcat)

Servlet

Response (HTML) → Client
```

### Static vs Dynamic Pages


- **Static Page**: Already made, directly served from server
- **Dynamic Page**: Built at runtime by servlet

### Web Container (Servlet Container)


- Also called **helper application**
- Examples: Tomcat, GlassFish, JBoss, WebSphere
- **Tomcat** is most commonly used for learning and development

### Deployment Descriptor


- **File**: `[Link]`
- Maps URL requests to specific servlets
- Contains two main tags:
- `<servlet>` - Defines servlet class
- `<servlet-mapping>` - Maps URL pattern to servlet

```xml
<servlet>
<servlet-name>ABC</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ABC</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
```

### Servlet 3.0+ Alternative


- Use **annotations** instead of XML
- Cleaner, less verbose
- Example: `@WebServlet("/add")`

---

## 2. Eclipse Setup & Configuration

### Required Software


1. **Eclipse IDE** - Java EE version
2. **Apache Tomcat** - Servlet container
3. **JDK** - Java Development Kit

### Eclipse Installation


1. Download Eclipse IDE for Java EE Developers
2. Extract and run `[Link]` (Windows) or equivalent
3. Select workspace folder for projects

### Eclipse Interface


- **Project Explorer** (left): All projects
- **Code Window** (center): Write code
- **Console/Servers** (bottom): Output and server management
- **Perspectives**: Java EE vs Java

---

## 3. Tomcat Configuration

### Download Tomcat


1. Search "Apache Tomcat download"
2. Choose version (8.0 or 9.0)
3. Download:
- Core zip file
- Source code (for documentation)
### Configure in Eclipse
1. Go to **Servers** tab
2. Click "No servers available" link
3. Select **Apache → Tomcat v8.0** (or v9.0)
4. Browse to Tomcat installation folder
5. Click **Finish**

### Test Tomcat


1. Start server in Eclipse
2. Open browser: `[Link]
3. Should see Tomcat homepage

### Common Issues


- **Port conflict**: Change port in server configuration (double-click server)
- Default port: 8080
- Alternative: 8081, 8082, etc.

---

## 4. Creating First Web Project

### Create Dynamic Web Project


1. File → New → Dynamic Web Project
2. **Project name**: DemoApp
3. **Target runtime**: Apache Tomcat
4. **Dynamic web module version**: 3.1
5. Check "Generate [Link] deployment descriptor"
6. Click **Finish**

### Project Structure


```
DemoApp/
├── Java Resources/
│ └── src/ (Java code here)
├── WebContent/
│ ├── META-INF/
│ ├── WEB-INF/
│ │ └── [Link] (deployment descriptor)
│ └── [Link] (public pages)
```

### Create HTML Page


1. Right-click WebContent → New → HTML File
2. Name: `[Link]`
3. Add basic content:

```html
<body>
<h1>Hello World</h1>
</body>
```

### Run Application


1. Right-click project → Run As → Run on Server
2. Select Tomcat server
3. Application opens in internal browser
4. To use external browser:
- Window → Web Browser → Select Firefox/Chrome

---

## 5. Creating First Servlet

### HTML Form Example


```html
<form action="add">
Enter first number: <input type="text" name="num1"><br>
Enter second number: <input type="text" name="num2"><br>
<input type="submit">
</form>
```

### Create Servlet Class


1. Right-click project → New → Class
2. **Package**: `[Link]`
3. **Name**: `AddServlet`
4. Extend `HttpServlet`

```java
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class AddServlet extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// Get parameters from request
int i = [Link]([Link]("num1"));
int j = [Link]([Link]("num2"));

// Perform operation
int k = i + j;

// Send response
PrintWriter out = [Link]();
[Link]("Result is " + k);
}
}
```

### Configure in [Link]


```xml
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
```

### Key Points


- Servlet must extend `HttpServlet`
- Use `service()` method to handle requests
- `HttpServletRequest` - receives data from client
- `HttpServletResponse` - sends data to client
- `PrintWriter` - writes response to client page

---

## 6. GET and POST Methods

### HTTP Methods


- **GET**: Fetch data from server
- Data visible in URL (query string)
- Example: `[Link]
- **POST**: Submit data to server
- Data not visible in URL
- More secure for sensitive information

### Specify Method in HTML


```html
<form action="add" method="post">
<!-- form fields -->
</form>
```

### Servlet Methods


Instead of `service()`, use specific methods:

```java
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// Handle GET requests only
}

public void doPost(HttpServletRequest req, HttpServletResponse res)


throws IOException {
// Handle POST requests only
}
```

### Service Method Hierarchy


- Request always goes to `service()` first
- `service()` internally calls `doGet()` or `doPost()`
- Based on request type
- Can implement both methods for flexibility

---

## 7. Calling Servlet from Servlet

### Two Approaches


1. **RequestDispatcher** (forward)
2. **sendRedirect** (redirect)

### RequestDispatcher (Forward)

#### Use Case


- Both servlets on same website
- Share same request/response objects
- Client doesn't know about forwarding
- URL doesn't change

#### Code Example


```java
// In AddServlet
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
int i = [Link]([Link]("num1"));
int j = [Link]([Link]("num2"));
int k = i + j;

// Add to request for next servlet


[Link]("k", k);

// Forward to SquareServlet
RequestDispatcher rd = [Link]("sq");
[Link](req, res);
}
```

```java
// In SquareServlet
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// Get data from request
int k = (int) [Link]("k");
k = k * k;

PrintWriter out = [Link]();


[Link]("Result is " + k);
}
```

### sendRedirect (Redirect)

#### Use Case


- Servlets on different websites (e.g., payment gateway)
- Client knows about redirect
- URL changes
- Two separate requests

#### Code Example


```java
// In AddServlet
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
int i = [Link]([Link]("num1"));
int j = [Link]([Link]("num2"));
int k = i + j;

// Redirect to SquareServlet
[Link]("sq?k=" + k); // URL rewriting
}
```

```java
// In SquareServlet
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// Get data from parameter
int k = [Link]([Link]("k"));
k = k * k;

PrintWriter out = [Link]();


[Link]("Result is " + k);
}
```

### Comparison

Feature RequestDispatcher sendRedirect

Objects Same request/response New request/response

URL Doesn't change Changes

Client awareness Not aware Aware

Data sharing Via request attributes Via URL/session

Server Same server Can be different

---

## 8. HttpServletRequest & HttpServletResponse

### HttpServletRequest Object


**Purpose**: Carries data from client to server

**Common Methods**:
```java
// Get form parameters
String value = [Link]("fieldName");

// Get/Set attributes (for servlet-to-servlet)


[Link]("key", value);
Object obj = [Link]("key");

// Get request info


String method = [Link](); // GET, POST
String uri = [Link]();

// Get session
HttpSession session = [Link]();

// Get RequestDispatcher
RequestDispatcher rd = [Link]("url");
```

### HttpServletResponse Object


**Purpose**: Carries data from server to client

**Common Methods**:
```java
// Get writer to send text
PrintWriter out = [Link]();
[Link]("HTML content");

// Set content type


[Link]("text/html");
[Link]("application/json");

// Redirect
[Link]("url");

// Add cookie
Cookie cookie = new Cookie("name", "value");
[Link](cookie);
```

### Request-Response Flow


```
Client → Request Object → Servlet → Response Object → Client
```

---
## 9. Session Management

### Why Session Management?


- HTTP is stateless
- Need to maintain data across multiple requests
- Share data between servlets

### Three Techniques


1. **URL Rewriting**
2. **HttpSession**
3. **Cookies**

---

### 1. URL Rewriting

**Concept**: Pass data via query string in URL

```java
// Servlet 1
int k = i + j;
[Link]("sq?k=" + k);

// Servlet 2
int k = [Link]([Link]("k"));
```

**Limitations**:
- Data visible in URL
- Not secure for sensitive data
- Cumbersome for multiple values

---

### 2. HttpSession

**Concept**: Server-side storage for user data

**Advantages**:
- Data persists across requests
- Not visible to client
- Can store objects

#### Create and Use Session


```java
// Servlet 1 - Store data
HttpSession session = [Link]();
[Link]("k", k);

// Servlet 2 - Retrieve data


HttpSession session = [Link]();
int k = (int) [Link]("k");
```

#### Session Methods


```java
// Get session (create if doesn't exist)
HttpSession session = [Link]();

// Get session (don't create)


HttpSession session = [Link](false);

// Set attribute
[Link]("key", value);

// Get attribute
Object obj = [Link]("key");

// Remove attribute
[Link]("key");

// Invalidate session
[Link]();
```

**Use Cases**:
- Login information
- Shopping cart
- User preferences

---

### 3. Cookies

**Concept**: Client-side storage sent with each request

**Analogy**: Token system in restaurant


- Shop gives token on first visit
- Show token on return visit to prove identity
#### Create and Send Cookie
```java
// Servlet 1 - Create cookie
Cookie cookie = new Cookie("k", k + ""); // Must be String
[Link](cookie);
```

#### Retrieve Cookie


```java
// Servlet 2 - Get cookies
Cookie[] cookies = [Link]();

for (Cookie c : cookies) {


if ([Link]().equals("k")) {
int k = [Link]([Link]());
// Use k
}
}
```

#### Cookie Methods


```java
// Create
Cookie cookie = new Cookie("name", "value");

// Set properties
[Link](3600); // Seconds (1 hour)
[Link]("/"); // Available to entire app

// Add to response
[Link](cookie);

// Get from request


Cookie[] cookies = [Link]();
```

### Session Management Comparison

Technique Storage Visibility Use Case

URL Rewriting Client (URL) Visible Simple, one-time data

HttpSession Server Hidden Secure, complex data

Cookies Client Hidden* User preferences


*Cookies can be viewed in browser dev tools

---

## 10. ServletConfig & ServletContext

### Purpose
- Provide initial configuration parameters
- Access at servlet startup
- Avoid hardcoding values

---

### ServletConfig

**Scope**: Single servlet

**Use Case**: Servlet-specific configuration

#### Configure in [Link]


```xml
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>[Link]</servlet-class>

<init-param>
<param-name>name</param-name>
<param-value>Suresh</param-value>
</init-param>
</servlet>
```

#### Access in Servlet


```java
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
ServletConfig cfg = getServletConfig();
String name = [Link]("name");

PrintWriter out = [Link]();


[Link]("Hi " + name);
}
```
**Key Points**:
- Each servlet has its own ServletConfig
- Different servlets can have different values for same parameter
- Perfect for servlet-specific settings

---

### ServletContext

**Scope**: Entire application (all servlets)

**Use Case**: Application-wide configuration

#### Configure in [Link]


```xml
<context-param>
<param-name>name</param-name>
<param-value>Navin</param-value>
</context-param>

<context-param>
<param-name>phone</param-name>
<param-value>Samsung</param-value>
</context-param>
```

#### Access in Servlet


```java
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
ServletContext ctx = getServletContext();
// OR: ServletContext ctx = [Link]();

String name = [Link]("name");


String phone = [Link]("phone");

PrintWriter out = [Link]();


[Link]("Hi " + name);
[Link]("Phone: " + phone);
}
```

**Key Points**:
- Only one ServletContext per application
- Shared by all servlets
- Use for: database URLs, file paths, global settings

---

### Comparison

Feature ServletConfig ServletContext

Scope Single servlet All servlets

Objects One per servlet One per application

Configuration `<init-param>` in `<servlet>` `<context-param>`

Access `getServletConfig()` `getServletContext()`

Use Case Servlet-specific Application-wide

---

## 11. Servlet Annotations (3.0+)

### Why Annotations?


- **Cleaner**: No verbose XML
- **Easier**: Configuration near code
- **Modern**: Industry standard

### Replace [Link] with Annotations

#### Old Way ([Link])


```xml
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
```

#### New Way (Annotation)


```java
package [Link];
import [Link];
import [Link];

@WebServlet("/add")
public class AddServlet extends HttpServlet {
// servlet code
}
```

### Important Points


1. **Slash required**: Must use `/add`, not `add`
2. **No [Link] needed**: Can have empty or delete it
3. **Can coexist**: XML and annotations can work together
4. **XML takes priority**: If both exist, XML overrides

### Multiple URL Patterns


```java
@WebServlet(urlPatterns = {"/add", "/addition", "/sum"})
public class AddServlet extends HttpServlet {
// servlet code
}
```

### With Init Parameters


```java
@WebServlet(
urlPatterns = "/add",
initParams = {
@WebInitParam(name = "name", value = "Navin"),
@WebInitParam(name = "phone", value = "Samsung")
}
)
public class AddServlet extends HttpServlet {
// servlet code
}
```

---

## Complete Working Example

### Project Structure


```
DemoApp/
├── Java Resources/
│ └── src/
│ └── [Link]/
│ ├── [Link]
│ └── [Link]
├── WebContent/
│ ├── WEB-INF/
│ │ └── [Link] (optional with annotations)
│ └── [Link]
```

### [Link]
```html
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form action="add" method="get">
Enter first number: <input type="text" name="num1"><br>
Enter second number: <input type="text" name="num2"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
```

### [Link] (with annotations)


```java
package [Link];

import [Link];
import [Link];
import [Link].*;

@WebServlet("/add")
public class AddServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws IOException {
int i = [Link]([Link]("num1"));
int j = [Link]([Link]("num2"));
int k = i + j;
// Store in session
HttpSession session = [Link]();
[Link]("k", k);

// Redirect to square servlet


[Link]("sq");
}
}
```

### [Link] (with annotations)


```java
package [Link];

import [Link];
import [Link];
import [Link];
import [Link].*;

@WebServlet("/sq")
public class SquareServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws IOException {

HttpSession session = [Link]();


int k = (int) [Link]("k");
k = k * k;

PrintWriter out = [Link]();


[Link]("Result is " + k);
}
}
```

---

## Best Practices

### 1. Use Annotations


- Cleaner than XML
- Configuration close to code
- Industry standard
### 2. Method Choice
- Use `doGet()` for fetching data
- Use `doPost()` for submitting/sensitive data
- Avoid `service()` unless handling both

### 3. Session Management


- Use HttpSession for secure data
- Use Cookies for user preferences
- Avoid URL rewriting for sensitive data

### 4. Resource Management


```java
PrintWriter out = null;
try {
out = [Link]();
// use out
} finally {
if (out != null) [Link]();
}
```

### 5. Error Handling


```java
try {
int i = [Link]([Link]("num1"));
} catch (NumberFormatException e) {
// Handle invalid input
[Link]("Invalid number format");
}
```

---

## Common Issues & Solutions

### 1. Port 8080 Already in Use


**Solution**: Change Tomcat port
- Double-click server in Eclipse
- Change HTTP port to 8081 or 8082
- Save and restart

### 2. 404 Error


**Causes**:
- URL mapping incorrect
- Servlet not registered (no annotation/XML)
- Wrong URL in form action

### 3. Null Pointer Exception


**Causes**:
- `getParameter()` returns null (missing form field)
- `getAttribute()` returns null (data not set)
- Session expired

### 4. Number Format Exception


**Cause**: Invalid input in number field
**Solution**: Validate before parsing
```java
String num = [Link]("num1");
if (num != null && ![Link]()) {
int i = [Link](num);
}
```

### 5. Cannot Forward After Response Committed


**Cause**: Writing to response before forwarding
**Solution**: Forward first, then write

---

## Quick Reference Card

### Essential Imports


```java
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
```

### Request Methods


```java
String value = [Link]("name");
Object obj = [Link]("key");
[Link]("key", value);
HttpSession session = [Link]();
RequestDispatcher rd = [Link]("url");
[Link](req, res);
```
### Response Methods
```java
PrintWriter out = [Link]();
[Link]("text");
[Link]("text/html");
[Link]("url");
[Link](cookie);
```

### Session Methods


```java
HttpSession session = [Link]();
[Link]("key", value);
Object obj = [Link]("key");
[Link]("key");
[Link]();
```

### Cookie Methods


```java
Cookie c = new Cookie("name", "value");
[Link](c);
Cookie[] cookies = [Link]();
[Link]();
[Link]();
```

---

## Key Takeaways

1. **Servlets** are Java classes that handle web requests


2. Extend **HttpServlet** for web applications
3. Use **doGet()** and **doPost()** for HTTP methods
4. **RequestDispatcher** forwards (same request)
5. **sendRedirect** redirects (new request)
6. **HttpSession** for server-side data storage
7. **Cookies** for client-side data storage
8. **Annotations** replace XML configuration
9. **ServletConfig** for servlet-specific settings
10. **ServletContext** for application-wide settings

---
## Next Steps

1. Learn **JSP (JavaServer Pages)**


2. Study **Filters** and **Listeners**
3. Explore **MVC Pattern** with Servlets
4. Learn **Spring MVC** framework
5. Practice building complete web applications

---

nd of Notes

You might also like