Serv Lets

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Servlets

1. Session in Servlets

We all know that HTTP is a stateless protocol. All requests and responses are independent.
But sometimes you need to keep track of client's activity across multiple requests. For eg.
When a User logs into your website, not matter on which web page he visits after logging in,
his credentials will be with the server, until he logs out. So this is managed by creating a
session.

Session Management is a mechanism used by the Web container to store session


information for a particular user. There are four different techniques used by Servlet
application for session management. They are as follows:

1. Cookies
2. Hidden form field
3. URL Rewriting
4. HttpSession

Session is used to store everything that we can get from the client from all the requests the
client makes.

How Session Works


The basic concept behind session is, whenever a user starts using our application, we can
save a unique identification information about him, in an object which is available throughout
the application, until its destroyed. So wherever the user goes, we will always have his
information and we can always manage which user is doing what. Whenever a user wants to
exit from your application, destroy the object with his information.

HttpSession?

HttpSession object is used to store entire session with a specific client. We can store, retrieve
and remove attribute from HttpSession object. Any servlet can have access
to HttpSession object throughout the getSession() method of the HttpServletRequest object.

How HttpSession works

1. On client's first request, the Web Container generates a unique session ID and gives it
back to the client with response. This is a temporary session created by web container.
2. The client sends back the session ID with each request. Making it easier for the web
container to identify where the request is coming from.
3. The Web Container uses this ID, finds the matching session with the ID and associates
the session with the request.
HttpSession Interface

Some Important Methods of HttpSession

Methods Description

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

String getId() returns a string containing the unique identifier assigned to the
session.
long getLastAccessedTime() returns the last time the client sent a request associated with
the session

int getMaxInactiveInterval() returns the maximum time interval, in seconds.

void invalidate() destroy the session

boolean isNew() returns true if the session is new else false

void setMaxInactiveInterval(int Specifies the time, in seconds,after servlet container will


interval) invalidate the session.

2. Cookies
Cookies are small pieces of information that are sent in response from the web server to the
client. Cookies are the simplest technique used for storing client state.

Cookies are stored on client's computer. They have a lifespan and are destroyed by the client
browser at the end of that lifespan.

Using Cookies for storing client state has one shortcoming though, if the client has turned of
Cookie saving settings in his browser then, client state can never be saved because the
browser will not allow the application to store cookies.

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

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

Cookies are created using Cookie class present in Servlet API. Cookies are added
to responseobject using the addCookie() method. This method sends cookie information over
the HTTP response stream. getCookies() method is used to access the cookies that are added
to response object.

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.

4.Servlets and Concurrency

A Java servlet container or web server is multithreaded and multiple requests to the same
servlet may be executed at the same time. Therefore, we need to take concurrency into
consideration while writing servlet.

As we discussed earlier that one and only one instance of Servlet gets created and for every
new request , Servlet Container spawn a new thread to execute doGet() or doPost() methof of
a servlet.

By default servlets are not thread safe because multiple threads can execute a single
instance of a program and therefore shares instance variables and could possibly be
attempting to read and write those shared variable.and it is a responsibility of a servlet
developer to take care of it.

Here are certain points which we should consider while writing servlets.

1. Service() , doGet(), doPost() or to be more generic doXXX() methods should not update or
modify instance variables as instance variables are shared by all threads of same instance.

2. If you have a requirement which requires modification of instance variable then do it in a


synchronized block.

3. Above two rules are applicable for static variables also because they are also shared.

4. Local variables are always thread safe.

5. The request and response objects are thread safe to use because new instance of these are
created for every request into your servlet, and thus for every thread executing in your
servlet.

Below are the two approaches to make the thread safe

a. Synchronized the block where you are modifying instance or static variables.(refer below
code snipped).

We recommend to synchronize the block where your code modifies the instance
variables instead of synchronizing complete method for the sake of performance.

Note that we need to take a lock on servlet instance as we need to make the particular
servlet instance as tread safe.

b) Single Thread Model Implements SingleThreadModel interface to make our thread


single threaded which means only one thread will execute service() or doXXX() method at a
time. A single-threaded servlet is slower under load because new requests must wait for a free
instance in order to proceed