0% found this document useful (0 votes)
17 views8 pages

Servlet Notes2

The document provides an overview of the servlet life cycle, detailing the init, service, and destroy methods, along with session tracking techniques in Java servlets. It explains how servlets handle client requests and maintain user state through methods like cookies, hidden form fields, URL rewriting, and the HttpSession interface. Additionally, it covers the advantages and disadvantages of each session tracking technique, as well as practical examples of cookie creation and management.

Uploaded by

Riya Yohannan
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)
17 views8 pages

Servlet Notes2

The document provides an overview of the servlet life cycle, detailing the init, service, and destroy methods, along with session tracking techniques in Java servlets. It explains how servlets handle client requests and maintain user state through methods like cookies, hidden form fields, URL rewriting, and the HttpSession interface. Additionally, it covers the advantages and disadvantages of each session tracking technique, as well as practical examples of cookie creation and management.

Uploaded by

Riya Yohannan
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/ 8

Advanced Java

Unit 3 Servlet
3.4 Life cycle of Servlet
3.5 Execution process of Servlet Application
3.6 Session Tracking

Servlet Life Cycle


A servlet life cycle can be defined as the entire process from its creation till the destruction.
The following are the paths followed by a servlet
1. The servlet is initialized by calling the init () method.
2. The servlet calls service() method to process a client's request.
3. The servlet is terminated by calling the destroy() method.
4. Finally, servlet is garbage collected by the garbage collector of the JVM.
The following figure depicts a typical servlet life-cycle scenario.
1. First the HTTP requests coming to the server are delegated to the servlet container.
2. The servlet container loads the servlet before invoking the service() method.
3. Then the servlet container handles multiple requests by spawning multiple threads,
each thread executing the service() method of a single instance of the servlet.

Contact: [email protected] Call:9763 9763 33, 020-65009763 | 1


www.vertexitservices.com
Advanced Java

Servlet life cycle methods


The init() method :
The init method is designed to be called only once. It is called when the servlet is first
created, and not called again for each user request. So, it is used for one-time initializations,
just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The
init() method simply creates or loads some data that will be used throughout the life of the
servlet.
The init method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}

The service() method :


The service() method is the main method to perform the actual task. The servlet container
(i.e. web server) calls the service() method to handle requests coming from the client(
browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and
calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
The service () method is called by the container and service method invokes doGet, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service()
method but you override either doGet() or doPost() depending on what type of request you
receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 2
www.vertexitservices.com
Advanced Java

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The destroy() method :


The destroy() method is called only once at the end of the life cycle of a servlet. This method
gives your servlet a chance to close database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this:
public void destroy() {
// Finalization code...
}

Session Tracking in Servlets


1. Session simply means a particular interval of time.
2. Session Tracking is a way to maintain state (data) of an user. It is also known
as session management in servlet.
3. 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.
4. HTTP is stateless that means each request is considered as the new request. It is
shown in the figure given below:

Contact: [email protected] Call:9763 9763 33, 020-65009763 | 3


www.vertexitservices.com
Advanced Java

Why use Session Tracking?


To recognize the user It is used to recognize the particular user.

Session Tracking Techniques


There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Cookies in Servlet
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.

How Cookie works


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

Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie

Contact: [email protected] Call:9763 9763 33, 020-65009763 | 4


www.vertexitservices.com
Advanced Java

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

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.

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 constructs a cookie with a specified name and
value) value.
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
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 changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided
by other interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used
to add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.

How to create Cookie?


Let's see the simple code to create cookie.
Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
response.addCookie(ck);//adding cookie in the response

How to delete Cookie?


Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

Contact: [email protected] Call:9763 9763 33, 020-65009763 | 5


www.vertexitservices.com
Advanced Java

How to get Cookies?


Let's see the simple code to get all the cookies.
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
}

Simple example of Servlet Cookies


In this example, we are storing the name of the user in the cookie object and accessing it in
another servlet. As we know well that session corresponds to the particular user. So if you
access it from too many browsers with different values, you will get the different value.

2) 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.
This approach is better if we have to submit form in all the pages and we don't want to
depend on the browser.
Let's see the code to store value in hidden field.
<input type="hidden" name="uname" value="Vimal Jaiswal">
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

Real application of hidden form field


It is widely used in comment form of a website. In such case, we store page id or page name
in the hidden field so that each page can be uniquely identified.

Advantage of Hidden Form Field


1. It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:


1. It is maintained at server side.
2. Extra form submission is required on each pages.
3. Only textual information can be used.

Contact: [email protected] Call:9763 9763 33, 020-65009763 | 6


www.vertexitservices.com
Advanced Java

Example of using Hidden Form Field


In this example, we are storing the name of the user in a hidden textfield and getting that
value from another servlet.

3)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&??
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. From a Servlet, we
can use getParameter() method to obtain a parameter value.

Advantage of URL Rewriting


1. It will always work whether cookie is disabled or not (browser independent).
2. Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
1. It will work only with links.
2. It can send Only textual information.

Contact: [email protected] Call:9763 9763 33, 020-65009763 | 7


www.vertexitservices.com
Advanced Java

4) HttpSession interface
In such case, container creates a session id for each user.The container uses this id to
identify the particular user.An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.

How to get the HttpSession object ?


The HttpServletRequest interface provides two methods to get the object of HttpSession:
public HttpSession getSession():Returns the current session associated with this request, or
if the request does not have a session, creates one.
public HttpSession getSession(boolean create):Returns the current HttpSession associated
with this request or, if there is no current session and create is true, returns a new session.
Commonly used methods of HttpSession interface
1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Contact: [email protected] Call:9763 9763 33, 020-65009763 | 8


www.vertexitservices.com

You might also like