Servlet Concepts Complete
Servlet Concepts Complete
Servlets operate within a Servlet Container (e.g., Apache Tomcat), which manages their
lifecycle, threading, and security. When a client sends a request (such as submitting a form
or clicking a link), the request is processed by the servlet, which generates a response (such
as an HTML page or JSON data).
2. **Server Forwarding**: The web server receives the request and forwards it to the
servlet container.
3. **Processing**: The servlet processes the request, interacts with databases or other
services, and generates a response.
4. **Response to Client**: The response is sent back to the web browser for display.
• **GET Method:**
- Retrieves data from the server without modifying it.
- Parameters are included in the URL as query strings (e.g., example.com?id=123).
- Not suitable for sending sensitive data since it appears in the browser history.
- Can be bookmarked and cached by browsers.
• **POST Method:**
- Sends data to the server, usually used for submitting forms.
- Parameters are sent in the request body, making it more secure.
- Cannot be bookmarked or cached.
- No limit on the amount of data sent.
3. Life Cycle of a Servlet
The lifecycle of a servlet is managed by the servlet container and consists of three main
phases:
1. **Initialization (`init()`)**
- The servlet is loaded into memory when the server starts or when it receives its first
request.
- The `init()` method is called once to initialize the servlet.
2. **Service (`service()`)**
- The servlet handles client requests using the `service()` method.
- It calls `doGet()`, `doPost()`, or other HTTP-specific methods based on the request type.
3. **Destruction (`destroy()`)**
- When the server shuts down or the servlet is no longer needed, the `destroy()` method is
called.
- This method releases resources like database connections.
Session management techniques include cookies, URL rewriting, hidden form fields, and
HttpSession.
6. What is URL Rewriting and How it Works?
URL rewriting is a session tracking technique used when cookies are disabled. It works by
appending a unique session ID to the URL so that the server can identify the user.
Example:
Instead of: `http://example.com/home`
It becomes: `http://example.com/home;jsessionid=123456`
The session ID is carried in the URL as the user navigates through the website.
Types of Cookies:
• **Session Cookies** – Temporary cookies that are deleted when the browser is closed.
• **Persistent Cookies** – Stored for a longer duration and retained even after closing the
browser.
Cookies help in authentication (e.g., remembering login status) and user tracking (e.g.,
analytics, advertising).