0% found this document useful (0 votes)
10 views19 pages

Ajp 6th Chapter Self Notes

Servlets are Java programs that run on a server, responding to client requests and generating dynamic content, primarily using HTTP. The servlet life cycle includes loading, initialization, request handling, and destruction, with key methods such as init(), service(), and destroy(). Additionally, cookies and session tracking are essential for managing user data and maintaining state across multiple HTTP requests.

Uploaded by

hj05102006
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)
10 views19 pages

Ajp 6th Chapter Self Notes

Servlets are Java programs that run on a server, responding to client requests and generating dynamic content, primarily using HTTP. The servlet life cycle includes loading, initialization, request handling, and destruction, with key methods such as init(), service(), and destroy(). Additionally, cookies and session tracking are essential for managing user data and maintaining state across multiple HTTP requests.

Uploaded by

hj05102006
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
You are on page 1/ 19

6.

1 Introduction to Servlets
Definition
• Servlets are Java programs that run on a server.
• They respond to client requests (e.g., via XHTML) and dynamically generate content
displayed in the browser.
• Managed by a servlet container (e.g., Tomcat), which is part of a web server.
Key Features
• Work primarily with HTTP (hence called "HTTP Servlets").
• Purpose: Enhance web server functionality by generating dynamic content.
How Servlets Work?
Step-by-Step Process
1. Client Request
o Client writes a URL request in a browser.
2. Web Server Interaction
o Web server locates the requested servlet.
3. Servlet Execution
o Servlet processes the request, gathers data, and generates a dynamic web
page.
4. Response
o Web page is sent back to the client browser.
Diagram (Working of Servlets)

Advantages of Servlets
1. Efficient Performance
o Run in the web server's address space, reducing overhead.
2. Platform Independence
o Can run on any server (Java-enabled).
3. Request-Response Model
o Handles HTML form inputs, communicates with the database, and applies
business logic.
4. Dynamic Content
o Servlets generate content dynamically (e.g., user logs, access times).
5. Multi-user Support
o Servlets synchronize multiple requests for better coordination.
6. Concurrency
o Handle concurrent requests efficiently.

6.2 Life Cycle of a Servlet


A Servlet Life Cycle describes the phases a servlet undergoes(जातो) during its execution in a
web container.

Stages of Servlet Life Cycle


1. Loading and Instantiation :
• The servlet class is loaded into memory by the web container when the first request
for the servlet is received.
• A single instance of the servlet is created using the default constructor.
2. Initialization (init() method)
• The init() method is invoked by the web container to initialize the servlet.
• This is called only once during the servlet's life cycle.
• Purpose: To perform setup tasks like establishing database connections or initializing
resources.
public void init(ServletConfig config) throws ServletException {
// Initialization code
}
Key Points:
• It receives a ServletConfig object that provides initialization parameters and servlet
context.
• Called before the servlet can handle requests.
3. Request Handling (service() method)
• The service() method processes client requests and generates responses.
• It is called each time a request is made to the servlet.
• The web container passes HttpServletRequest and HttpServletResponse objects to
this method.
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
// Request-handling code
}
4. Destruction (destroy() method)
• The destroy() method is invoked when the servlet is no longer needed.
• Purpose: To release resources such as closing database connections or clearing
memory.
• This is called only once, just before the servlet instance is removed from memory.
• Syntax:
java
Copy code
public void destroy() {
// Cleanup code
}

Diagram of Servlet Life Cycle


1. Servlet Loaded → 2. init() Method → 3. service() Method (Repeatedly Called) → 4.
destroy() Method

6.3: Creating a Simple Servlet

Steps to Create a Servlet


Extend/Implement Servlet Interface:

1. Implement Servlet Interface: Must include javax.servlet


2. Extend GenericServlet or HttpServlet:

• GenericServlet : Predefined implementation of Servlet interface.


• HttpServlet : Child class of GenericServlet.

❖ Methods in HttpServlet
- Request get handled with the help of below method

GET vs POST
• doGet: Requests data (less secure, more efficient).
• doPost: Submits data (more secure, less efficient).
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// handle GET request
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// handle POST request
}
Simple Servlet Program

Explanation of the Code:


1. Imports:
o java.io.*: For input/output operations.
o javax.servlet.*: Contains the Servlet interface and classes.
o javax.servlet.http.*: Provides HttpServletRequest and HttpServletResponse.
2. Extending HttpServlet:
o The HelloServlet class extends HttpServlet to use servlet features.
3. doGet() Method:
o Handles HTTP GET requests.
o Writes the HTML content (Hello, World!) as a response to the client.
4. Content Type:
o response.setContentType("text/html"); specifies the response content is
HTML. This is MIME type
5. Response Writing:
o PrintWriter out = response.getWriter(); is used to send data back to the client.
o The HTML content (<h1>Hello, World!</h1>) is written inside the body of the
response.
How to Run This Servlet:
1. Save the File: Save the program as HelloServlet.java.
2. Compile: Compile it using javac HelloServlet.java.
3. Deploy:
o Place the compiled .class file in the WEB-INF/classes directory of your web
application.
4. Configure:
o Add an entry in the web.xml file of your application:
o web.xml is commonly knows as deployment descriptor . this is basically the
configuration file that describes how to map the url of the web application to
the servlet

5. Run: Access the servlet via a browser using http://localhost:8080/yourApp/hello.

Working of How Servlet Works ?


• Before learning the actual servlet programming it is very important to understand
how servlet works. (Refer Fig. 6.1.1)
1. When a client make a request for some servlet, he/she actually uses the Web
browser in which request is written as a URL.
2. The web browser then sends this request to Web server. The web server first finds
the requested servlet.
3. The obtained servlet gathers the relevant information in order to satisfy the client's
request and builds a web page accordingly.
4. This web page is then displayed to the client. Thus the request made by the client
gets satisfied by the servlets.

6.4 Servlet API


Two package to implement servlet :

6.1 Advantages
• The servlets are very efficient in their performance and get executed in the address
space of the belonging web server.
• The servlets are platform independent and can be executed on different web servers.
• The servlets working is based on Request-Response. Any HTML form can take the
user input and can forward this input to the servlet. The servlet can then be
responsible to communicate with the back-end database and manipulate the
required business logic. These servlets embedded on the web servers using Servlets
API.
• Servlets provide a way to generate the dynamic document. For instance: A servlet
can display the information of current user logged in, his logging time, his last access,
total number of access he made so far and so on.
• Multiple users can keep a co-ordination for some application among themselves
using servlets.
• Using servlets multiple requests can be synchronized and then can be concurrently
handled.
6.4 Servlet API Notes
The Servlet API provides the tools for building dynamic web applications. Two key
packages are used for servlet development:
1. javax.servlet: Contains core classes and interfaces for basic servlet functionalities.
2. javax.servlet.http: Contains additional classes and interfaces specifically for HTTP
servlets.

6.5 javax.servlet Package


This package is the backbone of the servlet API and includes important interfaces and
classes.

6.5.1.1 Servlet Interface


- The Servlet interface defines lifecycle methods. All servlets must implement this
interface.
6.5.1.2 ServletConfig Interface
The ServletConfig interface is used to fetch initialization parameters.

6.5.1.3 ServletContext Interface


This interface allows servlets to share data and log events.

6.5.1.4 ServletRequest Interface


The ServletRequest interface helps gather client request details.
6.5.1.5 ServletResponse Interface
The ServletResponse interface enables sending data back to the client.

Memory Tricks to Remember the Methods


1. Servlet Lifecycle:
o Think of init → service → destroy as "Initialize, Serve, and Dispose".
2. Request vs. Response:
o Request gathers client-side data (getProtocol, getContentLength, etc.).
o Response sets server-side output (setContentType, getWriter, etc.).
3. Config vs. Context:
o Config = Per servlet (e.g., name, parameters).
o Context = Shared across the application (e.g., logging, attributes).
6.5.2 Classes
The javax.servlet package includes essential classes for handling servlets:

6.5.2.1 GenericServlet Class


• Implements life cycle methods such as init(), service(), and destroy().
• Does not assume any protocol, hence "Generic."
• Implements both Servlet and ServletConfig interfaces.

6.6 javax.servlet.http Package


This package specializes in handling HTTP requests and responses.
6.6 javax.servlet.http Package
This package specializes in handling HTTP requests and responses.
6.7 Handling HTTP Requests and Responses
Web browsers communicate with web servers using HTTP requests.
Methods of Sending Data
1. GET Method:
o Appends data to the URL as a query string (e.g., ?key=value).
o Handled by the doGet() method in servlets.
o Example: http://localhost/hello?user=John&age=25
2. POST Method:
o Sends data in the body of the request for higher security.
o Handled by the doPost() method in servlets.
Memory Tricks to Remember Key Points
1. GenericServlet Methods: Think "Init → Serve → Destroy."
2. HTTP Request vs. Response:
o Request = Input from client.
o Response = Output to client.
3. GET vs. POST:
o GET = "Visible, Fast, Limited."
o POST = "Secure, Flexible, Slow."

Chapter 6: Cookies and Session Tracking

6.8 Cookies in Web Development


Definition
Cookies are small pieces of information stored on a user's computer by a server during
web browsing. They are often used to remember user preferences or track behavior.
• Common Uses: Advertising, user preferences, session tracking, etc.
• Advantages: Stores information locally, supports personalized user experiences.
• Risks: Can be misused to track user activity; security and privacy must be maintained.
Cookie Class in Servlets
The Cookie class in Java Servlets simplifies cookie creation and management.
Constructors:
1. Cookie()
2. Cookie(String name, String value)
Important Methods in the Cookie Class

Sr. Method Purpose


No.
1 public String getName() Returns the name of the cookie.
2 public String getValue() Returns the value of the cookie.
3 public void setName(String name) Sets or changes the name of the
cookie.
4 public void setValue(String Sets or changes the value of the
value)
cookie.
5 public void addCookie(Cookie c) Adds the cookie to the response
object.
6 public Cookie[] getCookies() Retrieves all cookies using the
request.

Steps to Create and Use Cookies in a Servlet


1. Create a Cookie:
Cookie cookie = new Cookie("user", "JohnDoe");
response.addCookie(cookie);
Retrieve Cookies:
Cookie[] cookies = request.getCookies();
for (Cookie c : cookies) {
System.out.println("Name: " + c.getName() + ", Value: " + c.getValue());
}
Examples
Set Cookie Example (mycookieservlet.java):
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class mycookieservlet extends HttpServlet {


public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String txt_data = req.getParameter("txt_data");
Cookie cookie = new Cookie("My_Cookie", txt_data);
res.addCookie(cookie);
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("Cookie set successfully");
pw.close();
}
}

Retrieve Cookie Example (getCookieServlet.java):


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

public class getCookieServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
for (Cookie cookie : cookies) {
pw.println("Cookie Name: " + cookie.getName() + ", Cookie Value: " +
cookie.getValue());
}
pw.close();
}
}
Output Example
Cookie Name: data
Cookie Value: 12345
6.9 Session Tracking
Definition
HTTP is a stateless protocol. Each request is independent of the previous one, and the
server cannot inherently remember previous interactions.
• Session Tracking: A mechanism to maintain state across multiple HTTP requests using
a session-ID.
• Session-ID: Unique identifier exchanged between the browser and server to track a
user’s session.
Techniques for Session Tracking
1. Cookies
2. URL Rewriting
3. Hidden Form Fields
4. HttpSession
Session Tracking in Servlets
In servlets, sessions can be managed using the HttpSession class.
Key Methods of HttpSession:

Method Purpose

HttpSession getSession() Returns the session object.

void setAttribute(String name, Object Stores a value in the session.


value)

Object getAttribute(String name) Retrieves the value associated with the


given name.

void removeAttribute(String name) Removes the value associated with the


given name.

Enumeration getAttributeNames() Lists all attribute names stored in the


session.
Example: Count User Visits
Servlet Program to Count User Visits
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionCounter extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
Integer count = (Integer) session.getAttribute("visitCount");
if (count == null) {
count = 1;
} else {
count++;
}
session.setAttribute("visitCount", count);
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("You have visited " + count + " times.");
pw.close();
}
}
You have visited 5 times.
Key Takeaways
1. Cookies store data on the client-side, while sessions manage state on the server-side.
2. Use HttpSession for secure, server-side session tracking.
3. Always validate and secure cookies to prevent misuse.
4. Practice example programs to master concepts.

You might also like