0% found this document useful (0 votes)
77 views47 pages

Unit IV - Servlet

The document provides information about servlets. It defines servlets as small programs that execute on the server side of a web connection. It describes the lifecycle of a servlet, which includes loading, initialization, request handling, and destruction. The document also discusses the Servlet API, including important interfaces like Servlet, ServletRequest, and ServletResponse, and how they are used to create HTTP servlets that can handle HTTP requests and responses.

Uploaded by

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

Unit IV - Servlet

The document provides information about servlets. It defines servlets as small programs that execute on the server side of a web connection. It describes the lifecycle of a servlet, which includes loading, initialization, request handling, and destruction. The document also discusses the Servlet API, including important interfaces like Servlet, ServletRequest, and ServletResponse, and how they are used to create HTTP servlets that can handle HTTP requests and responses.

Uploaded by

Hitesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Unit – IV

Servlet
Introduction
• Servlets are small programs that execute on the server side of a web
connection.
• Just as applets dynamically extend the functionality of a web browser,
servlets dynamically extend the functionality of a web server.
How web browsers and servers provide content to a user
• Consider a request for a static web page.
• A user enters a URL into a browser.
• The browser generates an HTTP request to the appropriate web server.
• The web server maps this request to a specific file.
• That file is returned in an HTTP response to the browser.
• The HTTP header in the response indicates the type of the content. The
Multipurpose Internet Mail Extensions (MIME) are used for this purpose.
• Now consider dynamic content:
• Assume that an online store uses a database to store information about its business.
• This would include items for sale, prices, availability, orders, and so forth.
• It wishes to make this information accessible to customers via web pages.
• The contents of those web pages must be dynamically generated to reflect the latest
information in the database.
Advantages of Servlet
• Performance is significantly better as compared to CGI (Common Gateway
Interface).
(CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response.)

• Servlets execute within the address space of a web server.


• It is not necessary to create a separate process to handle each client request.
• Servlets are platform-independent because they are written in Java.
• The Java security manager on the server enforces a set of restrictions to
protect the resources on a server machine.
• The full functionality of the Java class libraries is available to a servlet.
• It can communicate with applets, databases, or other software via the
sockets and RMI mechanisms.
The Servlet API
• Two packages contain the classes and interfaces that are required to
build servlets:

• javax.servlet

• javax.servlet.http
The javax.servlet Package Interfaces
Interface Description
Servlet Declares life cycle methods for a servlet.
ServletConfig Allows servlets to get initialization parameters.
ServletContext Enables servlets to log events and access
information about their
environment.

ServletRequest Used to read data from a client request.


ServletResponse Used to write data to a client response.
The javax.servlet Package Classes
Class Description
GenericServlet Implements the Servlet and ServletConfig
interfaces.
ServletInputStream Provides an input stream for reading requests
from a client.
ServletOutputStream Provides an output stream for writing responses
to a client.

ServletException Indicates a servlet error occurred.


UnavailableException Indicates a servlet is unavailable.
The javax.servlet.http Package Interfaces
Interface Description
HttpServletRequest Enables servlets to read data from an HTTP
request.
HttpServletResponse Enables servlets to write data to an HTTP
response.
HttpSession Allows session data to be read and written.
The javax.servlet.http Package Classes
Class Description
Cookie Allows state information to be stored on a client
machine.
HttpServlet Provides methods to handle HTTP requests and
responses.
HttpSessionEvent Encapsulates a session-changed event.
The Life Cycle of a Servlet
The Servlet life cycle mainly goes through four stages,
• Loading a Servlet.
• Initializing the Servlet.
• Request handling.
• Destroying the Servlet.

• The entire life cycle of a Servlet is managed by the Servlet container which uses
the javax.servlet.Servlet interface to understand the Servlet object and manage
it.
• Servlet container manages the Servlet object.
Source:
https://www.geeksf
orgeeks.org/
1. Loading a Servlet
The Servlet container performs two operations in this stage :

• Loading
• Loads the Servlet class.
• Instantiation
• Creates an instance of the Servlet. To create a new instance of the Servlet, the
container uses the no-argument constructor.
2. Initializing a Servlet
• After the Servlet is instantiated successfully, the Servlet container
initializes the Servlet object.
• The container initializes the Servlet object by invoking the
Servlet.init(ServletConfig) method.
• This method is used to initialize the resources, such as JDBC
datasource.
• If the Servlet fails to initialize, then it informs the Servlet container by
throwing the ServletException or UnavailableException.
3. Handling request
• After initialization, the Servlet object is ready to serve the client requests.
• To serve the request, the Servlet container performs the following
operations :
• It creates the ServletRequest and ServletResponse objects.
• If this is a HTTP request, then the Web container creates HttpServletRequest and
HttpServletResponse objects which are subtypes of the ServletRequest and
ServletResponse objects respectively.
• After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse)
• The service() method while processing the request may throw the
ServletException or UnavailableException or IOException.
4. Destroying a Servlet
• When a Servlet container decides to destroy the Servlet, it performs
the following operations:
• It allows all the threads currently running in the service method of the Servlet
instance to complete their jobs and get released.
• After currently running threads have completed their jobs, the Servlet
container calls the destroy() method on the Servlet instance.
Servlet Life Cycle Methods
There are three life cycle
methods of a Servlet :
• init()
• service()
• destroy()

Source: https://www.geeksforgeeks.org/
1. init() method
• init() method is called by the Servlet container to initialize the Servlet
• This method is called only once.

public class MyServlet implements Servlet


{
public void init(ServletConfig config) throws ServletException
{
//initialization code
}
//rest of code
}
2. service() method
• The service() method of the Servlet inform the Servlet about the client requests.
• This method uses ServletRequest object to collect the data requested by the client.
• This method uses ServletResponse object to generate the output content.

public class MyServlet implements Servlet


{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
// request handling code
}
// rest of code
}
3. destroy() method
• The destroy() method runs only once during the lifetime of a Servlet
and signals the end of the Servlet instance.

public void destroy()

• As soon as the destroy() method is activated, the Servlet container


releases the Servlet instance.
• It performs the garbage collection.
Creating a HTTP Servlet
• Java allows users to create
two types of servlets: Servlet ServletConfig
• Generic servlet
• Using javax.servlet package
• HTTP servlet
• Using javax.servlet.http package
GenericServlet

• Servlet and ServletConfig are


interfaces
• GenericServlet and HTTPServlet are HTTPServlet
classes
• To create generic servlet, create a sub
class of GenericServlet and override
the service() method.
import java.io.*;
import javax.servlet.*;

public class HelloServlet extends GenericServlet


{
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
Handling HTTP Requests and Responses
• The HttpServlet class provides specialized methods that handle the
various types of HTTP requests.
• A servlet developer typically overrides one of these methods. These
methods are
• doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and
doTrace( ).
Various Methods Defined by ServletRequest
Method Description

String getParameter(String pname) Returns the value of the parameter named pname.

String[ ] getParameterValues(String Returns an array containing values associated with the


name) parameter specified by name.
Enumeration getParameterNames( ) Returns an enumeration of the parameter names for this
request.

String getProtocol( ) Returns a description of the protocol. Like name, version


etc.
String getRemoteAddr( ) Returns the string equivalent of the client IP address.

String getRemoteHost( ) Returns the string equivalent of the client host name.

String getServerName( ) Returns the name of the server.


int getServerPort( ) Returns the port number.
Various Methods Defined by ServletResponse
Method Description

ServletOutputStream Returns a ServletOutputStream that can be


getOutputStream( ) used to write binary data to the response. An
throws IOException IllegalStateException is thrown if getWriter( )
has already been invoked for this request.
PrintWriter getWriter( ) Returns a PrintWriter that can be used to write
throws IOException character data to the response. An
IllegalStateException is thrown if
getOutputStream( )
has already been invoked for this request.
void setContentLength(int size) Sets the content length for the response to size.

void setContentType(String Sets the content type for the response to type.
type)
Various Methods Defined by HttpServletRequest
Method Description

Cookie[ ] getCookies( ) Returns an array of the cookies in this request.

String getHeader(String field) Returns the value of the header field named
field.

String getMethod( ) Returns the HTTP method for this request.

String getPathInfo( ) Returns any path information that is located


after the servlet path
and before a query string of the URL.
String getQueryString( ) Returns any query string in the URL.

String getRemoteUser( ) Returns the name of the user who issued this
request.
Various Methods Defined by HttpServletRequest
Method Description

String getRequestedSessionId( ) Returns the ID of the session.

StringBuffer getRequestURL( ) Returns the URL.

HttpSession getSession( ) Returns the session for this request. If a


session does not exist, one is created and then
returned.
HttpSession getSession(boolean If new is true and no session exists, creates
new) and returns a session for this request.
Otherwise, returns the existing session for this
request.
Various Methods Defined by HttpServletResponse
Method Description

void addCookie(Cookie cookie) Adds cookie to the HTTP response.

boolean containsHeader(String Returns true if the HTTP response header


field) contains a field
named field.
String encodeURL(String url) Determines if the session ID must be encoded
in the URL
identified as url. If so, returns the modified
version of url.
Otherwise, returns url. All URLs generated by
a servlet should
be processed by this method.
Various Methods Defined by HttpServletResponse
Method Description

void sendError(int c, String s) Sends the error code c and message s to the
throws IOException client.
void sendRedirect(String url) Redirects the client to url.
throws IOException
void setHeader(String field, Adds field to the header with value equal to
String value) value.
void setStatus(int code) Sets the status code for this response to code.
Handling a data from HTML to Servlet
• Input to servlet is given from the client in the form of name-value
pairs.
• To access this input the following methods are used:
String getParameter(String pname)
Enumeration getParameterNames()
String[] getParameterValues(String name)
• These methods are available in servletReqest interface.
Session Tracking
• HTTP protocol is stateless, means for web server every request is a
new request to process and they can’t identify if it’s coming from the
same client.
• But sometimes in web applications, we should know who the client is
and process the request accordingly.
• For example, a shopping cart application should know who is sending
the request to add an item and in which cart the item has to be added
or who is sending checkout request so that it can charge the amount
to correct client.
There are following ways which provide unique identifier in request and
response:
1. User Authorization
2. URL Rewriting
3. Hidden form fields
4. Cookies
5. Session
1. User Authorization
• This is the very common way where user provides authentication
credentials from the login page.
• Then pass the authentication information between server and client
to maintain the session.
• This is not very effective method because it wont work if the same
user is logged in from different browsers.
2. URL Rewriting
• A session identifier parameter can be appended with every request
and response to keep track of the session.

http://www.example.com/catalog.jsp?userid=123

• This is very tedious because we need to keep track of this parameter


in every response and make sure it’s not clashing with other
parameters.
3. Hidden form fields
• We can create a unique hidden field in the HTML and when user
starts navigating, we can set its value unique to the user and keep
track of the session.
• This method can’t be used with links because it needs the form to be
submitted every time request is made from client to server with the
hidden field.
• Also it’s not secure because we can get the hidden field value from
the HTML source and use it to hack the session.
4. Cookies
• A cookie is a small piece of data in the form of a name-value pair that
is sent by a Web server and stored by the browser on the client
machine.
• This information is used by the application running on the server side
to customize the web page according to the past history of
transactions from that client machine.
• A server can send one or more cookies to a browser in the headers of
a response.
javax.servlet.http.Cookie class provides the functionality of cookies
Method Description
Cookie() Constructor of Cookie class which is used to constructs a
cookie
Cookie(String name, String value) Constructor of Cookie class which is used to constructs a
cookie with a specified name and value.
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.

Method Description
public void addCookie(Cookie c) Method of HttpServletResponse interface is used to add
cookie in response object.
public Cookie[] getCookies() Method of HttpServletRequest interface is used to return
all the cookies from the browser.
Creating Cookie

//creating cookie object


Cookie c=new Cookie("user",“Rohit");

//adding cookie in the response


response.addCookie(c);
Deleting Cookie

//deleting value of cookie


Cookie c=new Cookie("user","");

//changing the maximum age to 0 seconds


c.setMaxAge(0);

//adding cookie in the response


response.addCookie(c);
Getting Cookies

Cookie c[]=request.getCookies();
for(int i=0;i<c.length;i++)
{
//printing name and value of cookie
out.print("<br>"+c[i].getName()+"
"+c[i].getValue());
}
Cookie have the following disadvantages:

• They can only keep textual information.


• They’re browser dependent. Hence, if the client disables them, your
web application can’t make use of them
• Individual cookie can contain not more than 4kb of information
5. Session
• Session is a conversional state between client and server.
• It can consists of multiple request and response between client and server.
• HTTP is a stateless protocol. Each request is independent of the previous
one.
• In some applications, it is necessary to save state information so that
information can be collected from several interactions between a browser
and a server.
• Sessions provide such a mechanism.
• The only way to maintain a session is the unique session (session id) is
passed between server and client in every request and response.
• Servlet API provides Session management through HttpSession
interface.
• We can get session from HttpServletRequest object using following
methods:
Method Description

HttpSession getSession() This method always returns a HttpSession


object. It returns the session object attached
with the request, if the request has no
session attached, then it creates a new
session and return it.

HttpSession This method returns HttpSession object if


getSession(boolean flag) request has session else it returns null.
Some of the important methods of HttpSession are:

Method Description

public String getId() Returns the unique session id


It returns the time when this session was
public long getCreationTime() created, measured in milliseconds since
midnight January 1, 1970 GMT.

public long It returns the time when this session was last
accessed, measured in milliseconds since
getLastAccessedTime() midnight January 1, 1970 GMT.

It returns the time when this session was last


public long accessed, measured in milliseconds since
getLastAccessedTime()
midnight January 1, 1970 GMT.
• When we use HttpServletRequest getSession() method and it creates
a new request, it creates the new HttpSession object.
• It also add a Cookie to the response object with name JSESSIONID and
value as session id.
• This cookie is used to identify the HttpSession object in further
requests from client.
• If the cookies are disabled at client side and we are using URL
rewriting then this method uses the jsessionid value from the request
URL to find the corresponding session.
• JSESSIONID cookie is used for session tracking, so we should not use it
for our application purposes to avoid any session related issues.

You might also like