Chap 06 Servlets
Chap 06 Servlets
CHAPTER 05
SERVLET
The Objectives Of This Chapter Are:
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. So, before creating a Servlet object, let’s first understand the life
cycle of the Servlet object which is actually understanding how the Servlet
container manages the Servlet object.
• Loading a Servlet.
• Initializing the Servlet.
• Request handling.
• Destroying the Servlet.
LOADING A SERVLET:
Loading a Servlet: The first stage of the Servlet
lifecycle involves loading and initializing the
Servlet by the Servlet container. The Web
container or Servlet Container can load the
Servlet at either of the following two stages.
If the Servlet is not preceding stage, it may
delay the loading process until the Web
container determines that this Servlet is needed
to service a request.
•Loading : Loads the Servlet class.
•Init : Creates an instance of the Servlet. To
create a new instance of the Servlet, the
container uses the no-argument constructor.
SERVLET API
1. Servlet Interface
2. ServletRequest Interface
3. ServletResponse Interface
4. ServletConfig Interface
5. ServletContext Interface
Servlet interface provides common behavior to all the servlets. Servlet interface
defines methods that all servlets must implement. Servlet interface needs to be
implemented for creating any servlet (either directly or indirectly). It provides 3 life
cycle methods that are used to initialize the servlet, to service the requests, and to
destroy the servlet.
Method Description
public void init(ServletConfig initializes the servlet. It is the life cycle method of
config) servlet and invoked by the web container only once.
public void service(ServletRequest provides response for the incoming request. It is
request,ServletResponse response) invoked at each request by the web container.
public void destroy() is invoked only once and indicates that servlet is
being destroyed.
SERVLETRESPONSE INTERFACE
The response object allows you to format and send the response back to the client.
First we will see the commonly used methods in the ServletReponse.
Methods Description
PrintWriter getWriter() returns a PrintWriter object that can send character text to
the client.
void setBufferSize(int size) Sets the preferred buffer size for the body of the response
void setContentLength(int Sets the length of the content body in the response In
len) HTTP servlets, this method sets the HTTP Content-
Length header
void setContentType(String sets the content type of the response being sent to the
type) client before sending the respond.
SERVLETREQUEST INTERFACE
An object of ServletRequest is used to provide the client request information to a servlet such as
content type, content length, parameter names and values, header information's, attributes etc.
Method Description
public String getParameter(String is used to obtain the value of a parameter by
name) name.
public String[] returns an array of String containing all values
getParameterValues(String name) of given parameter name. It is mainly used to
obtain values of a Multi select list box.
public int getContentLength() Returns the size of the request entity data, or -
1 if not known.
public String Returns the character set encoding for the
getCharacterEncoding() input of this request.
SERVLETREQUEST INTERFACE
Method Description
public String getContentType() Returns the Internet Media Type of the
request entity data, or null if not known.
public ServletInputStream Returns an input stream for reading binary
getInputStream() throws data in the request body.
IOException
public String getServerName() Returns the host name of the server that
received the request.
public int getServerPort() Returns the port number on which this
request was received.
ServletConfig Interface
An object of ServletConfig is created by the web container for each servlet. This object can
be used to get configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to
change the servlet. So it is easier to manage the web application if any specific content is
modified from time to time.
How to get the object of ServletConfig
1.getServletConfig() method of Servlet interface returns the object of ServletConfig
1.The object of ServletContext provides an interface between the container and servlet.
2.The ServletContext object can be used to get configuration information from the web.xml
file.
3.The ServletContext object can be used to set, get or remove attribute from the web.xml file.
4.The ServletContext object can be used to provide inter-application communication.
SERVLETCONTEXT INTERFACE
1.ServletContext available in javax.servlet.*; package
2.ServletContext object is global to entire web application
3.Object of ServletContext will be created at the time of web application
deployment
4.Scope: As long as web application is executing, ServletContext object
will be available, and
5.it will be destroyed once the application is removed from the server.
6.ServletContext object will be available even before giving the first
request
GENERICSERVLET CLASS
GenericServlet class
implements Servlet, ServletConfig and Serializable interfaces. It
provides the implementation of all the methods of these interfaces except
the service method.
GenericServlet class can handle any type of request so it is protocol-
independent.
You may create a generic servlet by inheriting the GenericServlet class
and providing the implementation of the service method.
Methods of GenericServlet class
1.public void init(ServletConfig config) is used to initialize the servlet.
2.public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time when user
requests for a servlet.
3.public void destroy() is invoked only once throughout the life cycle and indicates that
servlet is being destroyed.
4.public ServletConfig getServletConfig() returns the object of ServletConfig.
5.public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
6.public void init() it is a convenient method for the servlet programmers, now there is no
need to call super.init(config)
7.public ServletContext getServletContext() returns the object of ServletContext.
8.public String getInitParameter(String name) returns the parameter value for the given
parameter name.
9.public String getServletName() returns the name of the servlet object.
HTTPSERVLET CLASS
The HttpServlet class extends the GenericServlet class and implements Serializable interface.
It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
1.public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected
service method by converting the request and response object into http type.
2.protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the
service method, and dispatches the request to the method depending on the incoming http request type.
3.protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is
invoked by the web container.
4.protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is
invoked by the web container.
5.protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It
is invoked by the web container.
6.protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS
request. It is invoked by the web container.
7.protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is
invoked by the web container.
HTTPSERVLETREQUEST INTERFACE
• String getContextPath() : This method is used to get the portion of the requested URI.
• Cookie[] getCookies() : This method is used to get all the Cookie the object in an array.
• java.lang.String getHeader(java.lang.String name) : This method is used to get the given
request header.
• java.util.Enumeration<java.lang.String> getHeaderNames() : This method is used to get all
the header names of the current request.
• HttpSession getSession() : This method is used to get the current session or creates a new
session if the request doesn't have session.
• java.lang.String getRequestedSessionId() : This method is used to get the id of the current
session.
HTTPSERVLETREQUEST METHODS
The doPost() method in servlets is used to process the HTTP POST requests. It is used
to submit the data from the browser to the server for processing. The data submitted
with POST method type is sent in the message body so it is secure and cannot be seen
in the URL. And there is no limit on the data that can be sent through the POST
method.
SESSIONCLASS
There are two methods declared in the HttpSessionListener interface which must be
implemented by the servlet programmer to perform some action.
Disadvantage of Cookies
3.It will not work if cookie is disabled from the browser.
4.Only textual information can be set in Cookie object.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides
a lot of useful methods for cookies.
Constructor of Cookie class
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.
1.For adding cookie or getting the value from the cookie, we need some methods
provided by other interfaces. They are:
2.public void addCookie(Cookie ck):method of HttpServletResponse interface is used
to add cookie in response object.
3.public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in
seconds.
public String getName() Returns the name of the cookie. The name
cannot be changed after creation.
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.
COOKIE EXAMPLE