servelet Java Servlet Life Cycle
Java Servlets are server-side Java components for dynamic The Java Servlet life cycle defines the phases a servlet
web content in applications like e-commerce. Introduced in undergoes, from creation to termination, managed by a
1997, they run in containers (e.g., Tomcat) to process servlet container (e.g., Apache Tomcat). It consists of three
requests and deliver dynamic responses. key methods in the [Link] interface, controlling
Need for Dynamic Content: Static HTML lacks personalization initialization, request handling, and cleanup for dynamic web
or real-time updates. Servlets generate dynamic responses applications.
from user input or databases, surpassing less scalable CGI. 1. Initialization (init): The init(ServletConfig config) method is
Technology: Part of Jakarta EE, servlets use the Servlet API, called once after the servlet is instantiated. It sets up
extending HttpServlet for HTTP operations, with resources like database connections or reads configuration
multithreading, session management, and integration with from [Link] or annotations. If it fails, the servlet isn’t used.
JSP, JDBC, and Spring.__What Servlets Do: Servlets handle java
HTTP requests, execute logic (e.g., form processing, database public void init(ServletConfig config) throws ServletException {
queries), and return dynamic responses (HTML, JSON), }
managing sessions and asynchronous tasks. 2. Request Handling (service): The service(ServletRequest req,
Advantages:-Better Performance: Multithreading handles ServletResponse res) method is invoked for each client
concurrent requests efficiently, outperforming CGI. request. In HttpServlet, it delegates to methods like doGet() or
Portability: Runs on any Java-compatible server. doPost() based on the HTTP method, processing form data or
Robust: Java’s stable framework ensures reliability for generating responses like HTML/JSON.
complex applications.__Secure: Filters and listeners provide java
strong authentication and data protection. public void service(ServletRequest req, ServletResponse res)
Technology:-Servlets, defined by the Servlet API throws ServletException, IOException {
([Link]), run in containers like Tomcat, managing }
lifecycle (init, service, destroy). They extend HttpServlet for protected void doGet(HttpServletRequest req,
HTTP methods, using annotations, filters, and listeners for HttpServletResponse res) throws ServletException,
configuration and security. They integrate with JSP, JDBC, and IOException {
Spring for modularity. }
What Servlets Do:-Servlets process HTTP requests via 3. Destruction (destroy): The destroy() method is called once
doGet()/doPost(), handling form data, database queries, or when the container removes the servlet (e.g., server
API calls, and generating dynamic responses. They manage shutdown). It releases resources like database connections.
sessions, support file uploads, and enable asynchronous tasks java
for scalability. public void destroy() {
}
Java Servlet APIT:--he Java Servlet API, part of Jakarta EE
(formerly Java EE), is a standard interface for building Add of 2 num
dynamic web applications in Java. Defined in the <html><body>
<form action="add" method="post">
[Link] package (previously [Link]), it provides
Num 1: <input type="text" name="n1"><br>
classes and interfaces for servlets to handle HTTP requests
Num 2: <input type="text" name="n2"><br>
and responses efficiently within a servlet container (e.g., <input type="submit" value="Add">
Apache Tomcat, Jetty). </form></body></html>
Key Components:__Servlet Interface: The core interface, import [Link].*;
defining lifecycle methods: init(ServletConfig) for import [Link].*;
initialization, service(ServletRequest, ServletResponse) for import [Link].*;
request handling, and destroy() for cleanup. Developers import [Link].*;
implement or extend this for custom servlets. @WebServlet("/add")
HttpServlet Class: Extends GenericServlet to handle HTTP- public class AddNumbers extends HttpServlet {
specific requests (GET, POST, etc.) via methods like doGet(), public void doPost(HttpServletRequest req,
doPost(), doPut(), and doDelete(). Most servlets extend this HttpServletResponse res) throws ServletException,
class.__ServletConfig: Provides initialization parameters and IOException {
servlet context during init().__ServletContext: Enables [Link]("text/html");
servlets to share data and access application-wide resources. PrintWriter out = [Link]();
ServletRequest/Response: Interfaces to process client int sum = [Link]([Link]("n1")) +
requests (e.g., form data) and generate responses (e.g., [Link]([Link]("n2"));
HTML, JSON).__Filters: Intercepts requests/responses for [Link]("<html><body>Sum: "+sum+"<br><a
tasks like logging or [Link]: Monitors href='[Link]'>Back</a></body></html>");
lifecycle events (e.g., session creation)._Features: Supports }
session management (HttpSession), asynchronous processing, }
and annotations (Servlet 3.0+) for simplified configuration. It
Basic calculator Authentication
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <head>
<form action="Calc" method="post"> <title>Login Page</title>
Number 1: <input type="text" name="num1"><br> </head>
Number 2: <input type="text" name="num2"><br> <body>
Operation: <h2>Login</h2>
<select name="op"> <form action="LoginServlet" method="post">
<option value="add">+</option> Username: <input type="text"
<option value="sub">-</option> name="username"><br><br>
<option value="mul">×</option> Password: <input type="password"
<option value="div">÷</option> name="password"><br><br>
</select><br> <input type="submit" value="Login">
<input type="submit" value="Calculate"> </form>
</form> </body>
</body> </html>
</html> import [Link].*;
import [Link].*; import [Link].*;
import [Link].*; import [Link].*;
import [Link].*; public class LoginServlet extends HttpServlet {
public class Calc extends HttpServlet { protected void doPost(HttpServletRequest request,
public void doPost(HttpServletRequest req, HttpServletResponse response)
HttpServletResponse res) throws ServletException, IOException {
throws ServletException, IOException { [Link]("text/html");
[Link]("text/html"); PrintWriter out = [Link]();
PrintWriter out = [Link](); String username = [Link]("username");
double num1 = String password = [Link]("password");
[Link]([Link]("num1")); if ("admin".equals(username) &&
double num2 = "password123".equals(password)) {
[Link]([Link]("num2")); HttpSession session = [Link]();
String op = [Link]("op"); [Link]("username", username);
double result = 0; [Link]("[Link]");
if ([Link]("add")) result = num1 + num2; } else {
else if ([Link]("sub")) result = num1 - num2; [Link]("<html><body>");
else if ([Link]("mul")) result = num1 * num2; [Link]("<h3>Invalid username or
else if ([Link]("div")) result = num1 / num2; password!</h3>");
[Link]("<html>"); [Link]("<a href='[Link]'>Try again</a>");
[Link]("<body>"); [Link]("</body></html>");
[Link]("Result: " + result); }
[Link]("<br><a href='[Link]'>Back</a>"); }
[Link]("</body>"); }
[Link]("</html>");
}
}
Session Creation & Working Session tracking in the Servlet API maintains user data
What’s a Session?: A session stores user data (like name, ID) across multiple HTTP requests, as HTTP is stateless. The
on the server to track it across multiple requests. HTTP is HttpSession interface enables this by creating a session with
stateless, so sessions help maintain user info. a unique JSESSIONID, sent to the client as a cookie or via
How’s It Created?: Use [Link](true) to create a URL rewriting. The server stores data (key-value pairs) in the
session or get an existing one. It generates a unique ID session, linked to the ID, and retrieves it when the client
(JSESSIONID) sent to the client via a cookie or URL. sends the ID back. Key methods include
How It Works: [Link](true) to create/get a session,
Server creates a session ID and stores data (key-value pairs) [Link]() to store data, [Link]()
linked to it. to retrieve data, and [Link]() to destroy the
Client sends the session ID with every request (via cookie or session. Timeout is set using
URL). [Link](). For cookie-less clients,
Server uses the ID to fetch the stored data. [Link]() appends the session ID to URLs.
Sessions expire after a timeout (e.g., 30 minutes) of inactivity. Snippet:
Use: Store stuff like user preferences or cart items across HttpSession session = [Link](true); //
pages. Create/get session
Code Snippet (Session Creation):Bare minimum, just session [Link]("userName", "JohnDoe"); // Store data
creation and use, no extra stuff: String user = (String) [Link]("userName"); //
HttpSession session = [Link](true); Retrieve data
[Link]("userData", "JohnDoe"); [Link]().println("Tracked: " + user);
[Link](30 * 60); This stores "JohnDoe" and retrieves it using JSESSIONID
[Link]().println("Session set! Data: " + from the client’s cookie. Another servlet can use
[Link]("userData")); [Link](false) to access the same data. Use
How the Snippet Works HTTPS for security and [Link]() for logout.
[Link](true): Creates a new session or gets the Timeout example: [Link](30 * 60)
existing one. (30 minutes).
setAttribute("userData", "JohnDoe"): Stores "JohnDoe" with
key "userData" in the session. 1. What is a Cookie?
setMaxInactiveInterval(30 * 60): Sets session to expire after 30 A cookie is a small piece of text data that a web server
minutes. stores on the client’s browser to maintain state information
Output: Shows "Session set! Data: JohnDoe" in the browser. between HTTP requests. Since HTTP is stateless, cookies
Destroy Session Snippet help in tracking sessions, storing user preferences, login info,
HttpSession session = [Link](false); etc.
if (session != null) { Characteristics:
[Link](); • Stored on client-side.
[Link]().println("Session destroyed!"); • Sent with each request to the server.
} • Has attributes like name, value, expiry, path,
domain, and security flags.
import [Link].*; 2. Types of Cookies
import [Link].*; 1. Based on Lifetime:
import [Link].*; Session Cookies:
public class SessionExample extends HttpServlet { Temporary, deleted when the browser is closed.
public void doGet(HttpServletRequest request, Example: login session.
HttpServletResponse response) Persistent Cookies:
throws ServletException, IOException { Stored on disk, valid for a specified period.
[Link]("text/html"); Example: “Remember Me” feature.
PrintWriter out = [Link](); [Link] on Accessibility:
// Session create karna (agar pehle se na ho) First-Party Cookies:
HttpSession session = [Link](true); Set by the website you visit.
// Session attribute set karna Third-Party Cookies:
[Link]("username", "Ayush"); Set by external domains (ads, analytics).
[Link]("<h1>Session created successfully!</h1>"); Explanation:
[Link]("<p>Username in session: " + [Link](true): Naya session create karta hai agar
[Link]("username") + "</p>"); pehle se exist na ho.
[Link]("<p>Session ID: " + [Link]() + "</p>"); [Link]("key", value): Session mein data store
} karta hai.
} [Link](): Session ID display karta hai.