6 Servlets

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 138

6.

SERVLETS 14 Marks
Mr.Ghanawajeer D.J.
SYLLABUS
• 6.1. The Life Cycle of Servlet

• 6.2. Creating Simple Servlet: The

Servlet API javax.servlet Package:

Servlet Interface, ServletConfig

Interface, ServletContext Interface

1
SYLLABUS
• 6.2. Creating Simple Servlet:The

Servlet API javax.servlet Package:

ServletRequest Interface,

ServletResponse Interface,

GenericServlet class

2
SYLLABUS
• 6.3. The javax.servlet.http Package:

HttpServletRequest Interface, HttpServletResponse

Interface, HttpSession Interface, Cookie Class,

HttpServlet Class, HttpSessionEvent class,

HttpSessionBindingEvent Class

3
SYLLABUS
• 6.4. Handling HTTP Request and Response,

Handling HTTP GET Request ,Handling HTTP

POST Request

• 6.5. Cookies and Session Tracking

4
INTRODUCTION
• Servlet is a Technology that is used to create web
application.
• Web component that is deployed on server side to create
dynamic web pages.
• Servlet is an API that provides many Interfaces and classes
including documentation.
• Servlet is an Interface that must be implemented for creating
any servlet.
5
INTRODUCTION
• Servlet is a class that extend the functionalities of server
and responds to the incoming requests.

• A servlet is like an applet, but on the server side.

• Here focus on both sides of a client-server relationship.

• The client requests that some action be performed and the


server performs the action and responds to the client.

6
INTRODUCTION
• This request-response model of communication is the
foundation for the highest-level view of networking in Java
servlets.

• A common implementation of the request-response model is


between World Wide Web browsers and World Wide Web
servers.

7
INTRODUCTION
• When a user selects a Web site to browse through their
browser (the client application), a request is sent to the
appropriate Web server (the server application).

• The server normally responds to the client by sending the


appropriate HTML Web page.

8
OVERVIEW OF SERVLET
TECHNOLOGY

9
INTRODUCTION
• A servlet extends the functionality of a server. The
javax.servlet package and the javax.servlet.http package
provide the classes and interfaces to define servlets.

• Servlet technology today is primarily designed for use with


the HTTP protocol of the Web, but servlets are being
developed for other technologies.

10
INTRODUCTION
• A Servlet is a Java program that runs on a Web server. It is
similar to an applet, but is processed on the server rather
than a client's machine.
• Servlets are often run when the user clicks a link, submits a
form, or performs another type of action on a website.

11
INTRODUCTION
• The Servlet APIs are now developed by the Apache group
(www.apache.org).
• Before you can program with servlets, you must download
and install the Apache group's implementation of servlets
called Tomcat.
• You may download Tomcat at no charge from Sun
Microsystems at the Website:
java.sun.com/products/jsp/tomcat

12
INTRODUCTION
• After downloading Tomcat, install it on your system and
carefully read the readme file supplied in the doc directory.

• It explains how to set up Tomcat and discusses how to start


the server that can be used to test servlets if you do not have
a Web server that supports servlets.

13
INTRODUCTION
• To develop servlets, you also need to copy the servlet.jar file
containing the servlet class files from the installation
directory to your JDK extensions directory (the directory
c:\jdk1.3\jre\lib\ext on Windows or the directory
~/jdk1.3/jre/lib/ext on UNIX).

14
OVERVIEW OF SERVLET
TECHNOLOGY
• Servlets are the analog on the server side to applets on the
client side. Servlets are normally executed as part of a Web
server.
• In fact, Servlets have become so popular that they are now
supported by most major Web servers, including the
Netscape Web servers, Microsoft's Internet Information
Server (IIS), the World Wide Web Consortium's Jigsaw Web
server and the popular Apache Web server.

15
OVERVIEW OF SERVLET
TECHNOLOGY
• The Servlets in this chapter show the communication
between clients and servers via the HTTP protocol of the
World Wide Web.

• A client sends an HTTP request to the server. The server


receives the request and directs it to be processed by
appropriate servlets.

16
OVERVIEW OF SERVLET
TECHNOLOGY

17
DIRECTORY STRUCTURE

ROOT Save
.java program

18
TYPES OF SERVLET
• Generic Servlet:
• javax.servlet (package)
• extends javax.servlet.Servlet
• service method
• Http Servlet:
• javax.servlet.http (package)
• extends javax.servlet.HttpServlet
• doget(), doPost()….
19
SERVLET APPLICATION
ARCHITECTURE

20
THE SERVLET API
• We discuss at a high level the servlet related classes,
methods and exceptions. Architecturally, all servlets must
implement the Servlet interface.

• The methods of interface Servlet are invoked automatically


by the server on which the servlet is installed.

21
THE SERVLET API
• The servlet packages define two abstract classes that
implement the interface Servlet - class GenericServlet (from
the package javax.servlet) and class HttpServlet (from the
package javax.servlet.http).

22
THE SERVLET API
(JAVAX.SERVLET)
Interfaces:
• Servlet:Declare a life cycle methods for servlet.
• ServletConfig:Allows servlets to initialization parameters
• ServletContext: Enables servlets to log events and access
information about their environment
• ServletRequest: used to read data from client request

23
THE SERVLET API
(JAVAX.SERVLET)
Interfaces:
• ServletResponse: used to write data from client response
• SingleThreadModel: Indicates that the servlet is thread safe

24
THE SERVLET API
(JAVAX.SERVLET)
Classes:
• GenericServlet: Implements the Servlet & ServletConfig
Interface.
• ServletInputStream: Encapsulates an input stream for
reading request from a client.
• ServletOutputStream: Encapsulates an output stream for
writing responses to client.

25
THE SERVLET API
(JAVAX.SERVLET)
Classes:
• ServletException: Indicates servlet errors occurred.
• UnavailableException: Indicates servlet is unavailable.

26
THE SERVLET API
(JAVAX.SERVLET)
Servlet:

• 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).
27
THE SERVLET API
(JAVAX.SERVLET)
Servlet:

• It provides 3 life cycle methods that are used to initialize the


servlet, to service the requests, and to destroy the servlet and
2 non-life cycle methods.

28
THE SERVLET API
(JAVAX.SERVLET)
Servlet: The Life Cycle of Servlet

Initialization
init()

Service
service()

doGet() Concurrent
doPost()
doDelete() Threads
doHead()
doTrace()
of Execution
doOptions()

Destruction
destroy()
29
THE SERVLET API
(JAVAX.SERVLET)
Servlet: Methods of Servlet Life Cycle

• init() :

– Servlet loads and initializes the servlet

• service():

– Servlet handles one or more client Request and


Responses to the client

30
THE SERVLET API
(JAVAX.SERVLET)
Servlet: Methods of Servlet Life Cycle

• destroy():

– Servlet is deactivated or server is terminated

– Memory allocated for the servlet and its object are


garbage collected

31
THE SERVLET API
(JAVAX.SERVLET)
Servlet: Methods of Servlet Life Cycle

• void init( ServletConfig config ):

• This method is automatically called once during a servlet's


execution cycle to initialize the servlet. The ServletConfig
argument is supplied automatically by the server that
executes the servlet.

32
THE SERVLET API
(JAVAX.SERVLET)
Servlet: Methods of Servlet Life Cycle

• ServletConfig getServletConfig()

• This method returns a reference to an object that implements


interface ServletConfig. This object provides access to the
servlet's configuration information such as initialization
parameters and the servlet's ServletContext, which provides
the servlet with access to its environment. (i.e., the server in
which the servlet is executing). 33
THE SERVLET API
(JAVAX.SERVLET)
Servlet: Methods of Servlet Life Cycle

• void service( ServletRequest request,ServletResponse


response )

• This is the first method called on every servlet to respond to


a client request.

34
THE SERVLET API
(JAVAX.SERVLET)
Servlet: Methods of Servlet Life Cycle

• String getServletInfo()

• This method is defined by a servlet programmer to return a


String containing servlet information such as the servlet's
author and version.

35
THE SERVLET API
(JAVAX.SERVLET)
Servlet: Methods of Servlet Life Cycle

• void destroy()

• This "cleanup" method is called when a servlet is terminated


by the server on which it is executing.

• This is a good method to use to deallocate a resource used


by the servlet (such as an open file or an open database
connection).
36
THE SERVLET API
(JAVAX.SERVLET)
Servlet: Example

37
THE SERVLET API
(JAVAX.SERVLET)
ServletConfig:

• The ServletConfig interface allows a servlet to obtain


configuration data when it is loaded.

• The ServletConfig is used for getting initialization values or


configuration values stored in web.xml. If we store any
configuration or initialization values in ServletConfig object
then it is available to only that particular servlet instance.
38
THE SERVLET API
(JAVAX.SERVLET)
ServletConfig: Methods

• String getInitParameter(String name)

• Gets the value of the initialization parameter with the given


name.

39
THE SERVLET API
(JAVAX.SERVLET)
ServletConfig: Methods

• Enumeration<String> getInitParameterNames()

• Returns the names of the servlet's initialization parameters


as an Enumeration of String objects, or an empty
Enumeration if the servlet has no initialization parameters.

40
THE SERVLET API
(JAVAX.SERVLET)
ServletConfig: Methods

• ServletContext getServletContext()

• Returns a reference to the ServletContext in which the


caller is executing.

• String getServletName()

• Returns the name of this servlet instance.

41
THE SERVLET API
(JAVAX.SERVLET)
<web-app>
ServletConfig: Example
<servlet>

......
<init-param>
Web.xml
<param-name>size</param-name>

<param-value>25</param-value>
</init-param>
......
</servlet>
</web-app>
42
THE SERVLET API
(JAVAX.SERVLET)
ServletConfig: Example
ServletConfig config=getServletConfig();
String str=config.getInitParameter(“size");

• This code can be used in servlet to read the initialized


parameters in web.xml.

43
THE SERVLET API
(JAVAX.SERVLET)
ServletContext:

• ServletContext is used for getting initialization values or


configuration values stored in web.xml. If we store any
configuration or initialization values in ServletContext
object then it is available to the entire servlet instance.

• All servlet instances will be having one ServletContext


object.
44
THE SERVLET API
(JAVAX.SERVLET)
ServletContext:

• ServletContext object can be accessed by all the servlets and


by all the users in the application. Only one ServletContext
instance will be created per application.

• Defines a set of methods that a servlet uses to communicate


with its servlet container, for example, to get the MIME type
of a file, dispatch requests, or write to a log file.
45
THE SERVLET API
(JAVAX.SERVLET)
ServletContext: Methods

• String getInitParameter(String name)

• Returns a String containing the value of the named context-


wide initialization parameter, or null if the parameter does
not exist.

46
THE SERVLET API
(JAVAX.SERVLET)
ServletContext: Methods

• Enumeration getInitParameterNames()

• Returns the names of the context's initialization parameters


as an Enumeration of String objects, or an empty
Enumeration if the context has no initialization parameters.

47
THE SERVLET API
(JAVAX.SERVLET)
ServletContext: Methods

• void setAttribute(String name,Object val)

• Binds an object to a given attribute name in this


ServletContext.

• Object getAttribute(String name)

• Returns the servlet container attribute with the given name,


or null if there is no attribute by that name.
48
THE SERVLET API
(JAVAX.SERVLET)
ServletContext: Methods

• void removeAttribute(String name)

• Removes the attribute with the given name from this


ServletContext.

• void log(String s)

• Writes to the servlet log.

49
THE SERVLET API
(JAVAX.SERVLET)
ServletContext: Example

50
THE SERVLET API
(JAVAX.SERVLET)
ServletRequest:

• This interface is for getting data from the client to the servlet
for a service request

• The methods are then used by servlets when the service


method is executed; the ServletRequest object is passed as
an argument to the service method.

51
THE SERVLET API
(JAVAX.SERVLET)
ServletRequest:

• 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.

52
THE SERVLET API
(JAVAX.SERVLET)
ServletRequest: Methods

• String getProtocol()

• Returns a description of the Protocol

• String getContentType()

• Returns the Internet Media Type of the request entity data,


or null if not known.

53
THE SERVLET API
(JAVAX.SERVLET)
ServletRequest: Methods

• int getContentLength()

• Returns the size of the request entity data, or -1 if not


known.

• int getServerPort()

• Returns the port number on which this request was received.

54
THE SERVLET API
(JAVAX.SERVLET)
ServletRequest: Methods

• String getRemoteAddr()

• Returns the string equivalent of client IP address.

• String getRemoteHost()

• Returns the clients Host Name.

55
THE SERVLET API
(JAVAX.SERVLET)
ServletRequest: Methods

• ServletInputStream getInputStream() throws


IOException

• Returns an input stream for reading binary data in the


request body.

• String getParameter(String name)

• is used to obtain the value of a parameter by name.


56
THE SERVLET API
(JAVAX.SERVLET)
ServletRequest: Example

57
THE SERVLET API
(JAVAX.SERVLET)
ServletResponse:

• This Interface used for sending MIME data from the


servlet's service method to the client.

• Its methods are then used by servlets when the service


method is run, to return data to clients.

• The ServletResponse object is passed as an argument to the


service method.
58
THE SERVLET API
(JAVAX.SERVLET)
ServletResponse:

• To write MIME bodies which consist of binary data, use the


output stream returned by getOutputStream.

• To write MIME bodies consisting of text data, use the writer


returned by getWriter.

59
THE SERVLET API
(JAVAX.SERVLET)
ServletResponse: Methods

• void setContentType(String type)

• Sets the content type for the response to type.

• PrintWriter getWriter() throws IOException

• Used to write a character data to the response

60
THE SERVLET API
(JAVAX.SERVLET)
ServletResponse: Methods

• ServletOutputStream getOutputStream() throws


IOException

• Used to write binary data to the response

61
THE SERVLET API
(JAVAX.SERVLET)
ServletResponse: Example

62
THE SERVLET API
(JAVAX.SERVLET)
GenericServlet:

• Implements the Servlet & ServletConfig interfaces. It


provides the implementation of all the methods of these
interfaces except the service method.

• A GenericServlet class can handle any type of request so it


is protocol-independent.

63
THE SERVLET API
(JAVAX.SERVLET)
GenericServlet:

• A GenericServlet is an abstract class and it has only one


abstract method, which is service().

• A GenericServlet that should always override the service()


method to handle the client request.

64
THE SERVLET API
(JAVAX.SERVLET)
GenericServlet:

• The service() method accepts two arguments ServletRequest


object and ServletResponse object.

• The request object tells the servlet about the request made
by client while the response object is used to return a
response back to the client.

65
THE SERVLET API
(JAVAX.SERVLET)
GenericServlet: Methods

• void init(ServletConfig config)

• This method is used to initialize the servlet.

• void destroy()

• This Method is invoked only once throughout the life cycle


and indicates that servlet is being destroyed.

66
THE SERVLET API
(JAVAX.SERVLET)
GenericServlet: Methods

• ServletConfig getServletConfig()

• It returns the object of ServletConfig.

• String getServletInfo()

• It returns information about servlet such as writer, copyright,


version etc.

67
THE SERVLET API
(JAVAX.SERVLET)
GenericServlet: Methods

• ServletContext getServletContext()

• It returns the object of ServletContext.

• String getInitParameter(String name)

• It returns the parameter value for the given parameter name.

68
THE SERVLET API
(JAVAX.SERVLET)
GenericServlet: Methods

• Enumeration getInitParameterNames()

• It returns all the parameters defined in the web.xml file.

• String getServletName()

• It returns the name of the servlet object.

69
THE SERVLET API
(JAVAX.SERVLET)
GenericServlet : Reading Servlet Parameters Example
<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/Dnyan/servlet/PostParameters">
<table>
<tr>
<td>employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
70
</tr>
THE SERVLET API
(JAVAX.SERVLET)
GenericServlet : Reading Servlet Parameters Example
<tr>
<td>phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="submit">
</body>
</html> 71
THE SERVLET API
(JAVAX.SERVLET)
GenericServlet : Reading Servlet Parameters Example
Enumeration e=req.getParameterNames()
while(e.hasMoreElements())
{
String pname=(String)e.nextElement();
pw.print(pname+”=“);
Stirng pvalue=req.getParameter(pname);
pw.println(pvalue);
}

72
THE SERVLET API
(JAVAX.SERVLET.HHTP)
Interfaces:
• HttpServletRequest: used to read data from an HTTP client
request.
• HttpServletResponse:used to write data to HTTP client
response.
• HttpSession: Allows session data to be read and write.

73
THE SERVLET API
(JAVAX.SERVLET.HHTP)
Classes:
• Cookie: Allows state information to be stored on a client
machine.
• HttpServlet: Provides methods to handle HTTP request &
responses.
• HttpSessionEvent: This is notified when session object is
changed.

74
THE SERVLET API
(JAVAX.SERVLET.HHTP)
Classes:
• HttpSessionBindingEvent: Events of this type are either sent
to an object that implements HttpSessionBindingListener
when it is bound or unbound from a session.

75
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletRequest:

• The Web server that executes the servlet creates an


HttpServletRequest object and passes this to the servlet's
service method (which, in turn, passes it to doGet or
doPost).

76
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletRequest:

• This object contains the request from the client. A variety of


methods are provided to enable the servlet to process the
client's request.

• Some of these methods are from interface ServletRequest-


the interface that HttpServletRequest extends.

77
THE SERVLET API
(JAVAX.SERVLET.HHTP)
HttpServletRequest : Methods

• String getParameter(String name )

• Returns the value associated with a parameter sent to the


servlet as part of a GET or POST request. The name
argument represents the parameter name.

78
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletRequest : Methods

• Enumeration getParameterNames()

• Returns the names of all the parameters sent to the


servlet as part of a POST request.

79
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletRequest : Methods

• String[] getParameterValues( String name )

• Returns a String array containing the values for a


specified servlet parameter.

80
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletRequest : Methods

• Cookie[] getCookies()

• Returns an array of Cookie objects stored on the client


by the server. Cookies can be used to uniquely identify
clients to the servlet.

81
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletRequest : Methods

• HttpSession getSession( boolean create )

• Returns an HttpSession object associated with the


client's current browsing session.

• An HttpSession object can be created by this method


(true argument) if an HttpSession object does not
already exist for the client.
82
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletRequest : Methods

• HttpSession objects can be used in similar ways to


Cookies for uniquely identifying clients.

83
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletResponse:

• Every call to doGet or doPost for an HttpServlet receives an


object that implements interface HttpServletResponse.

• The Web server that executes the servlet creates an


HttpServletResponse object and passes this to the servlet's
service method (which, in turn, passes it to doGet or
doPost).
84
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletResponse:

• This object contains the response to the client. A variety of


methods are provided to enable the servlet to formulate the
response to the client. Some of these methods are from
interface ServletResponse-the interface that
HttpServletResponse extends.

85
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletResponse : Methods

• void addCookie( Cookie cookie )

• Used to add a Cookie to the header of the response to


the client.

• The Cookies maximum age and whether the client


allows Cookies to be saved (Determine whether or not).

86
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletResponse : Methods

• ServletOutputStream getOutputStream()

• Obtains a byte-based output stream enabling binary data


to be sent to the client.

87
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletResponse : Methods

• PrintWriter getWriter()

• Obtains a character-based output stream enabling text


data to be sent to the client.

88
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletResponse : Methods

• void setContentType( String type )

• Specifies the MIME type of the response to the browser.


The MIME type helps the browser determine how to
display the data.

89
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServletResponse : Methods

• void setContentType( String type )

• Specifies the MIME type of the response to the browser.


The MIME type helps the browser determine how to
display the data.

90
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpSession:

• The HttpSession interface enables a servlet to read and write


the state information that is associated with an HTTP
session.

91
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpSession:

• A session contains information specific to a particular user


across the whole application. When a user enters into a
website (or an online application) for the first time
HttpSession is obtained via request.getSession(), the user is
given a unique ID to identify his session.

• This unique ID can be stored into a cookie or in a request


parameter. 92
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpSession : Methods

• Object getAttribute(String atr)

• Extracts a previously stored value from a session object.

• It Returns null if no value is associated with given atr.

93
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpSession : Methods

• void setAttribute(String atr, Object val)

• Associates a value val with attribute name passed in atr.


• void removeAttribute(String atr)

• Removes values associated with atr.

94
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpSession : Methods

• boolean isNew()

• Determines if session is new to client (not to page)


• long getCreationTime()

• Returns time at which session was first created.


• long getLastAccessedTime()

• Returns time at which session was last sent from client.


95
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServlet class:

• The HttpServlet class extends the GenericServlet class and


implements Serializable interface. It provides http specific
methods such as doGet, doPost… etc.

96
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServlet class:

• The two most common HTTP request types (also known as


request methods) are get and post.

• A get request gets (or retrieves) information from the server.

• Common uses of get requests are to retrieve an HTML


document or an image.

97
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServlet class:

• A post request posts (or sends) data to the server.

• Common uses of post requests are to send the to Webserver,


information from an HTML form in which the client enters
data to send to the server, information so that it can search
on the Internet, or query a database for the client, to send
authentication information to the server, etc.
98
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServlet : Methods

• void service(HttpServletRequest req,


HttpServletResponse res)

• Receives the request from the service method, and


dispatches the request to the doXXX() method
depending on the incoming http request type.

99
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServlet : Methods

• void doGet(HttpServletRequest req,


HttpServletResponse res)

• Handles the GET request. It is invoked by the web


container.

100
THE SERVLET API
(JAVAX.SERVLET.HTTP)
HttpServlet : Methods

• void doPost(HttpServletRequest req,


HttpServletResponse res)

• Handles the POST request. It is invoked by the web


container.

101
THE SERVLET API
(JAVAX.SERVLET.HTTP)
Cookies class:

• A Cookies is a small piece of information which contains


name and value both of type String.

• Cookies are stored at client side. We can use cookies to store


client specific data but it is not a good approach because
browser might not support cookies or client may delete
cookie. Also storing values in cookie is not secure.
102
THE SERVLET API
(JAVAX.SERVLET.HTTP)
Cookies Class : Methods

• void setDomain(String pattern)

• This method sets the domain to which cookie applies,


for example tutorialspoint.com.
• String getDomain()

• This method gets the domain to which cookie applies,


for example tutorialspoint.com. 103
THE SERVLET API
(JAVAX.SERVLET.HTTP)
Cookies Class : Methods

• 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.

104
THE SERVLET API
(JAVAX.SERVLET.HTTP)
Cookies Class : Methods

• 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.

105
THE SERVLET API
(JAVAX.SERVLET.HTTP)
Cookies Class : Methods

• String getName()

• This method returns the name of the cookie. The name


cannot be changed after creation.
• void setValue(String newValue)

• This method sets the value associated with the cookie.

106
THE SERVLET API
(JAVAX.SERVLET.HTTP)
Cookies Class : Methods

• String getValue()

• This method gets the value associated with the cookie.


• void setPath(String path)

• This method sets the path to which this cookie applies.

• String getPath()

• This method gets the path to which this cookie applies.


107
THE SERVLET API
(JAVAX.SERVLET.HTTP)
Cookies Class : Methods

• void setSecure(boolean flag)

• This method sets the boolean value indicating whether


the cookie should only when secure Protocol is being
used.

108
THE SERVLET API
(JAVAX.SERVLET.HTTP)
Handling HTTP Request & Response:

By Using GET Method


By Using POST Method

109
THE SERVLET API
(JAVAX.SERVLET.HTTP)
Handling HTTP GET Request: Example

110
THE SERVLET API
(JAVAX.SERVLET.HTTP)
Handling HTTP POST Request: Example

111
COOKIES AND SESSION TRACKING
Session Tracking:

• Session simply means a particular interval of time.

• Session Tracking is a way to maintain state (data) of an


user.

• It is also known as Session Management in servlet.

112
COOKIES AND SESSION TRACKING
Session Tracking:

• Http protocol is a stateless so we need to maintain state


using session tracking techniques.

• Each time user requests to the server, server treats the


request as the new request. So we need to maintain the
state of an user to recognize to particular user.

113
COOKIES AND SESSION TRACKING
Session Tracking:

• HTTP is stateless that means each request is considered


as the new request.

• It is used to recognize the particular user. 114


COOKIES AND SESSION TRACKING

Session Tracking: Tracking Techniques

• There are four techniques used in Session tracking:

Cookies

Hidden Form Field

URL Rewriting

HttpSession
115
COOKIES AND SESSION TRACKING
Session Tracking: Cookies

• A cookie is a small piece of information that is persisted


between the multiple client requests.

• A cookie has a name, a single value, and optional


attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

116
COOKIES AND SESSION TRACKING
Session Tracking: Cookies

• By default, each request is considered as a new request.

• In cookies technique, we add cookie with response from


the servlet.

• So cookie is stored in the cache of the browser.

117
COOKIES AND SESSION TRACKING
Session Tracking: Cookies

• After that if request is sent by the user, cookie is added


with request by default.

• Thus, we recognize the user as the old user.

118
COOKIES AND SESSION TRACKING
Session Tracking: Cookies

119
COOKIES AND SESSION TRACKING
Session Tracking: Cookies

• Types of Cookies:
• Non-persistent Cookie:

• It is valid for single session only. It is removed each time


when user closes the browser.

120
COOKIES AND SESSION TRACKING
Session Tracking: Cookies

• Types of Cookies:
• Persistent cookie:

• It is valid for multiple session. It is not removed each time


when user closes the browser. It is removed only if user
logout or sign out.

121
COOKIES AND SESSION TRACKING
Session Tracking: Cookies

• Advantages of Cookies:
• Simplest technique of maintaining the state.

• Cookies are maintained at client side.

122
COOKIES AND SESSION TRACKING
Session Tracking: Cookies

• Disadvantages of Cookies:
• It will not work if Cookie is disabled from the browser.

• Only textual information can be set in Cookie object.

123
COOKIES AND SESSION TRACKING
Session Tracking: Cookies Example

124
COOKIES AND SESSION TRACKING
Session Tracking: Hidden Form Field

• In case of Hidden Form Field a hidden (invisible)


textfield is used for maintaining the state of an user.

• In such case, we store the information in the hidden


field and get it from another servlet.

125
COOKIES AND SESSION TRACKING
Session Tracking: Hidden Form Field

• This approach is better if we have to submit form in all


the pages and we don't want to depend on the browser.

126
COOKIES AND SESSION TRACKING
Session Tracking: Hidden Form Field

• Let's see the code to store value in hidden field.


<input type="hidden" name="uname" value=“Karmayogi“>

• Here, uname is the hidden field name and Karmayogi is


the hidden field value.

127
COOKIES AND SESSION TRACKING
Session Tracking: Hidden Form Field Example

128
COOKIES AND SESSION TRACKING
Session Tracking: URL Rewriting

• In URL Rewriting, we append a token or identifier to


the URL of the next Servlet or the next resource.

• We can send parameter name/value pairs using the


following format:

url?name1=value1&name2=value2&??

129
COOKIES AND SESSION TRACKING
Session Tracking: URL Rewriting

• A name and a value is separated using an equal = sign, a


parameter name/value pair is separated from another
parameter using the ampersand(&).

• When the user clicks the hyperlink, the parameter


name/value pairs will be passed to the server.

130
COOKIES AND SESSION TRACKING
Session Tracking: URL Rewriting

• From a Servlet, we can use getParameter() method to


obtain a parameter value.

131
COOKIES AND SESSION TRACKING
Session Tracking: URL Rewriting

• Advantages of URL Rewriting:


• It will always work whether Cookie is disabled or not
(browser independent).

• Extra form submission is not required on each pages.

132
COOKIES AND SESSION TRACKING
Session Tracking: URL Rewriting

• Disadvantages of URL Rewriting:


• It will work only with links.

• It can send Only textual information.

133
COOKIES AND SESSION TRACKING
Session Tracking: URL Rewriting Example

134
COOKIES AND SESSION TRACKING
Session Tracking: HttpSession

• In such case, container creates a session id for each user.

• The container uses this id to identify the particular user.

135
COOKIES AND SESSION TRACKING
Session Tracking: HttpSession

• An object of HttpSession can be used to perform two


tasks:
Bind objects

View and manipulate information about a session, such


as the session identifier, creation time, and last accessed
time.
136
COOKIES AND SESSION TRACKING
Session Tracking: HttpSession Example

137

You might also like