0% found this document useful (0 votes)
3 views42 pages

Servlet Programming

Servlets are Java programs that run on web servers to handle requests and generate responses, operating on a server-side model. The servlet lifecycle includes methods such as init(), service(), and destroy() for initialization, request handling, and cleanup respectively. Servlets respond to HTTP requests using methods like doGet() and doPost(), and utilize HTTP headers for communication between clients and servers.
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)
3 views42 pages

Servlet Programming

Servlets are Java programs that run on web servers to handle requests and generate responses, operating on a server-side model. The servlet lifecycle includes methods such as init(), service(), and destroy() for initialization, request handling, and cleanup respectively. Servlets respond to HTTP requests using methods like doGet() and doPost(), and utilize HTTP headers for communication between clients and servers.
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

Servlet

Programming

Ashwitha K
Servlet Structure:

❖ Servlets are the Java programs that run on the Java-enabled web server or application server.
❖ They are used to handle the request obtained from the web server, process the request, produce the response,
then send a response back to the web server.
Properties of Servlets are as follows:
➢ Servlets work on the server-side.
➢ Servlets are capable of handling complex requests obtained from the web server.
3
Life cycle of a servlet(Servlet Life Cycle)
The web container maintains the life cycle of a servlet instance.

Servlet class is loaded

● Servlet is in new state.


Servlet instance is created

Init method is invoked ● Servlet comes in the ready state.

Service method is invoked

Destroy method is invoked ● Shifts to end state


4
init() Method is Invoked

➢ The web container calls the init() method only once, immediately after creating the servlet instance.
➢ This method is used to initialize the servlet before it starts handling client requests.
➢ The init() method is a life cycle method of the [Link] interface.
➢ It is mainly used to perform one-time tasks such as:
● Loading configuration parameters
● Establishing database connections
● Initializing resources

Syntax of init() Method


public void init(ServletConfig config) throws ServletException

ServletConfig config : Provides configuration information to the servlet, such as initialization parameters and servlet
context.

ServletException: Thrown if any error occurs during servlet initialization.

Example: public void init(ServletConfig config) throws ServletException


{
[Link]("Servlet initialized");
}
service method is invoked

● The web container calls the service() method every time a request is received for the servlet.
● If the servlet is not initialized, the container first:
○ Loads the servlet class
○ Creates the servlet instance
○ Calls the init() method
and then calls the service() method.

● If the servlet is already initialized, the container directly calls the service() method.
Note: The servlet is initialized only once, but the service() method is called for every client
request.
● The service() method is a life cycle method of the [Link] interface.
● It is responsible for processing client requests and generating responses.
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException
When a servlet extends HttpServlet, the service() method automatically routes the
request to:
➢ doGet() for GET requests
➢ doPost() for POST requests
➢ doPut(), doDelete() etc.

destroy method is invoked : public void destroy()

The web container calls the destroy() method before removing the servlet instance from
the service.
➢ Closing database connections
➢ Releasing memory
➢ Stopping threads
➢ Closing files or network resources
The destroy() method is a life cycle method of the [Link] interface.
Basic Servlet Structure 8

Servlets are mainly used to build dynamic web applications.

Basic Servlet handles GET request and


POST request.
doGet()
● Handles GET requests
● Used when data is sent through URL

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello from Servlet</h1>");
}

doPost()
● Handles POST requests
● Used when data is sent through forms securely

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
String name = [Link]("name");
PrintWriter out = [Link]();
[Link]("Welcome " + name);
}
Uses of Servlet Packages

Package Uses / Description


Name

[Link] Contains classes and interfaces that define the contracts between a servlet and the servlet
container. It provides core servlet functionality independent of any protocol.

[Link].h Contains classes and interfaces that define the contracts between a servlet and the servlet
ttp
container when using the HTTP protocol. It supports HTTP-specific features such as sessions,
cookies, and request methods.
HTTP Request Response:

● Java servlets operate on HTTP request -response model.

● HTTP is the communication protocol used between a web client (browser) and a
web server.
● Servlets act as server‑side Java programs that receive HTTP requests, process
them, and generate HTTP responses.
● The servlet API abstracts the low‑level details of HTTP and provides Java classes
and interfaces to handle requests and responses effectively.
● HTTP (HyperText Transfer Protocol) is an application‑layer, stateless protocol
used for client–server communication on the Web.
HTTP Request:

➢ An HTTP request is sent by a client to request a resource or to submit data to the server. In
Java, this request is represented by the HttpServletRequest interface.

Structure of HTTP Request


An HTTP request consists of:

1. Request Line
2. Request Headers
3. Optional Request Body

Request Line Format: METHOD Resource-URI HTTP-Version

Example:

GET /[Link] HTTP/1.1


HTTP Request Methods:

Servlets respond to different HTTP methods using corresponding Java methods.

HTTP Method Purpose Servlet Method


GET Retrieve data doGet()

POST Submit data doPost()


PUT Update data doPut()
DELETE Remove data doDelete()
HEAD Retrieve headers only doHead()
HttpServletRequest Interface

HttpServletRequest provides methods to access client request data:


● getParameter(String name) – Retrieves form data
● getHeader(String name) – Retrieves header values
● getMethod() – Returns HTTP method
● getRequestURI() – Returns requested URI
● getSession() – Accesses session object
HTTP Response

● An HTTP response is sent by the server after processing the request. In Java, the response is
represented by the HttpServletResponse interface.

Structure of HTTP Response


An HTTP response consists of:

1. Status Line
2. Response Headers
3. Response Body

Status Line Format:

HTTP-Version Status-Code Reason-Phrase


Example: HTTP/1.1 200 OK
HTTP Status Codes

Code Meaning
200 OK – Request successful
301 Moved Permanently
302 Found (Temporary Redirect)
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
500 Internal Server Error
HttpServletResponse Interface

This interface allows servlets to control the response sent to the client.

Common methods:

● setContentType(String type)
● setStatus(int sc)
● sendRedirect(String location)
● getWriter() – Sends text response
● getOutputStream() – Sends binary data
Servlet Request–Response Lifecycle

The servlet container manages the complete lifecycle:

1. Client sends HTTP request


2. Web server forwards request to servlet container
3. Container creates HttpServletRequest and HttpServletResponse objects
4. Appropriate servlet method (doGet() / doPost()) is invoked
5. Servlet processes request and writes response
6. Response is sent back to client
HTTP headers
● Metadata fields that accompany HTTP requests and responses, providing additional
context about the communication between clients and servers.
● Key-value pairs : content types, authentication credentials, caching behavior and
security policies.
● These key-value pairs carry essential metadata that tells servers and clients how to
communicate, what data formats to expect, and how to handle security and caching.

Example: HTTP header as a shipping label on a package.

The package contains the actual data (such as a product or document), but the label
provides the delivery system with important details, including where it originated, its
destination, handling instructions, and its contents.
The structure of HTTP headers

Header-Name: header-value

Example :GET /api/users/123 HTTP/1.1


Host: [Link]
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
How HTTP headers work:
1. HTTP headers facilitate communication throughout the entire
request-response cycle.
2. When a client initiates a request, it includes headers that provide context
about what it expects and what it can handle.
3. The server then processes these headers and returns a response with its
own set of headers.
1. Client prepares the request:
● The user opens a web browser and navigates to the login page of a website, say
[Link]/login.
● The browser assembles an HTTP request when the user submits their login credentials
(username and password) through a form.

The HTTP request might look like this:

POST /login HTTP/1.1


Host: [Link]
Content-Type: application/x-www-form-urlencoded
Content-Length: 47
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Cookie: sessionid=abc123
Accept: text/html,application/xhtml+xml,application/xml
● The headers like Content-Type and Accept indicate the type of data being sent and expected in
return.
● The body of the request contains the login details (e.g., username and password).
2. Headers travel with the request:

● The HTTP request, including the headers, is sent from


the browser to the server over the internet.
● The request travels through various intermediaries
like DNS servers, routers, and proxies until it reaches
the website's backend server.
3. Server processes headers:
Once the server receives the HTTP request, it examines the headers to
understand important details such as:
● Authentication: Does the request include valid credentials (e.g., a session
cookie or token)?
● Content types: What formats does the client accept (text/html,
application/json, etc.)?

In the case of a login page, the server will primarily check whether the
username and password are valid and whether the session is authorized.
4. Server generates response:
Based on the request, the server processes the login credentials. For example:
● If the credentials are correct, the server may create a session for the user and send a
200 OK response, redirecting them to the homepage.
● If the credentials are incorrect, the server responds with a 401 Unauthorized error,
instructing the client to try again.
The HTTP response headers might look like this:
HTTP/1.1 200 OK
Date: Sun, 28 Jan 2026 10:00:00 GMT
Content-Type: text/html; charset=UTF-8
Set-Cookie: sessionid=xyz789; HttpOnly
Location: /home
The server also sends a Set-Cookie header to store a session identifier, which will be
used for future requests.
5. Client receives and processes the response:
Once the response reaches the browser, it:
● Interprets the status code: The browser sees the 200 OK status code,
which means the login was successful.
● Processes response headers: The browser checks the Set-Cookie
header and stores the session ID to maintain the user's login state.
● Renders content: The browser then redirects the user to the homepage
(using the Location: /home header) and displays the appropriate content.
If the login failed (i.e., if the server sent a 401 Unauthorized response), the
browser would likely display a message like "Invalid username or
password" to the user.
Types of HTTP headers

● Request headers: Sent from the client to the server, containing information
about the request, the client’s capabilities, and what the client expects in return.
● Response headers: Sent from the server to the client, providing metadata
about the response, including how the client should handle the returned data.
● Representation headers: Describe the encoding, format, and other
characteristics of the message body in both requests and responses.
● Payload headers: Contain information about the payload data, including
content length, encoding, and range information for partial content delivery.
Example Request Headers:
GET /api/users/12345 HTTP/1.1
Host: [Link]
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124
Safari/537.36
Accept: application/json
Accept-Language: en-US,en;q=0.9
Authorization: Bearer abc123token
Cache-Control: no-cache
Example Response Headers:
HTTP/1.1 200 OK
Date: Sun, 28 Jan 2026 12:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 150
Cache-Control: no-store
Set-Cookie: sessionid=xyz456; HttpOnly; Secure
Request Representation Headers:
Accept: application/json
Accept-Encoding: gzip, deflate, br

Response Representation Headers:


Content-Type: application/json; charset=utf-8
Content-Encoding: gzip
Example Payload Headers:
Request Payload Headers:
Content-Type: application/json
Content-Length: 75

Response Payload Headers:


Content-Length: 250
Range: bytes=0-249
Common HTTP request headers:
Accept: The Accept header defines the media types that the client can process and
which formats it prefers. For example, Accept: application/json, text/html indicates
that the client prefers JSON or HTML responses.
User-Agent:The User-Agent header identifies the web browser or client application
making the request, which enables the server to tailor its response to the client’s
capabilities.
Authorization:The Authorization header is used to send the client’s credentials to
the server when accessing protected resources.
Content-Type:The Content-Type header identifies the media type of the content in
the request body. For example, Content-Type: application/json indicates that the
request body contains JSON data.
Cookie: The client uses the Cookie header to send previously stored
cookies back to the server. The server uses these cookies to associate the
request with a specific user or session.
Accept-Language: The Accept-Language header indicates the client’s
preferred natural languages for the response content.
Accept-Encoding: The Accept-Encoding header tells the server which
compression algorithms the client supports, allowing the server to compress
the response body and reduce bandwidth usage.
The Anatomy of a Cookie

● Cookies are usually set in an HTTP header .


● A servlet that sets a cookie might send headers that look something
like this −
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT;
path = /; domain = [Link]
Connection: close
Content-Type: text/html
If the user points the browser at any page that matches the path and domain
of the cookie, it will resend the cookie to the server.
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: [Link]
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name = xyz
A servlet will then have access to the cookie through the request method
[Link]() which returns an array of Cookie objects.
Servlet Cookies Methods

public void setDomain(String pattern) : This method sets the domain to


which cookie applies, for example [Link].
public String getDomain(): This method gets the domain to which cookie
applies, for example [Link].
public void setMaxAge(int expiry): This method sets how much time (in
seconds) should elapse before the cookie expires. If you don't set this, the
cookie will last only for the current session.
public int getMaxAge(): This method returns the maximum age of the cookie,
specified in seconds, By default, -1 indicating the cookie will persist until
browser shutdown.
public String getName() : This method returns the name of the cookie. The name
cannot be changed after creation.
public void setValue(String newValue): This method sets the value associated with
the cookie
public String getValue(): This method gets the value associated with the cookie.

public void setPath(String uri): This method sets the path to which this cookie
applies. If you don't specify a path, the cookie is returned for all URLs in the same
directory as the current page as well as all subdirectories.
public String getPath(): This method gets the path to which this cookie applies.

public void setSecure(boolean flag): This method sets the boolean value indicating
whether the cookie should only be sent over encrypted (i.e. SSL) connections.
Setting Cookies with Servlet

(1) Creating a Cookie object − You call the Cookie constructor with a
cookie name and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");

Keep in mind, neither the name nor the value should contain white space
or any of the following characters −
[]()=,"/?@:;
(2) Setting the maximum age − You use setMaxAge to specify how
long (in seconds) the cookie should be valid.
Following would set up a cookie for 24 hours.
[Link](60 * 60 * 24);

(3) Sending the Cookie into the HTTP response headers − You use
[Link] to add cookies in the HTTP response header as
follows −
[Link](cookie);
You are require to create a java servlet program that accepts first name and last
name as input from the user,stores these values in cookies and then display as the
users input along with a confirmation message on a newly generated HTML
[Link] cookies should expire after 24 hours.

1. Create the form for user input.


2. Write the java servlet code
Reading Cookies with Servlet
To read cookies, you need to create an array of
[Link] objects by calling the getCookies()
method of HttpServletRequest. Then cycle through the array, and
use getName() and getValue() methods to access each cookie and
associated value.
Delete Cookies with Servlet
To delete cookies is very simple.
● Read an already existing cookie and store it in Cookie object.
● Set cookie age as zero using setMaxAge() method to delete an existing
cookie
● Add this cookie back into response header.

You might also like