You are on page 1of 28

Topics to be covered

Statelessness of HTTP protocol

Business logic needs stateful protocol

What is a Session?
What is Session ID? What is Session Tracking? Hidden form fields URL Rewriting Cookies Session Tracking API

Topics to be covered
Creating session Setting new Attribute in Session Deleting session data Servlet Context scope Context scope attributes Redirect to another webpage Mechanism used by sendRedirct Using RequestDispatcher Cookeis Anatomy of cookeis Seting cookies with servlet Reading cookies with Servlet

Statelessness of HTTP protocol


Series of actions in http request-response protocol : A client opens a connection Requests some resource Server receives the request Generates the response Sends back the response to the client Closes the connection Once the connection is closed, the server cannot remember

any information about the client. So server considers the next request from the same client as a fresh client, with no relation to the previous request. So HTTP protocol is called stateless protocol.

Business logic needs stateful protocol


When there is a need to maintain the conversational

state, session tracking is needed. Ex:


In a shopping cart application a client keeps on adding

items into his cart using multiple requests. When every request is made, the server should identify in which clients cart the item is to be added. So in this scenario, there is a certain need for session tracking. Solution is, when a client makes a request it should introduce itself by providing unique identifier every time.

What is a Session?
A session is a conversation between the server and a client.

A conversation consists series of continuous request and response. A Session refers to sequence of all the requests that a single client makes to a server for a particular period. A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable is associated with that session. In case of web applications the default time-out value for session variable is 20 minutes, which can be changed as per the requirement.

What is Session ID?


A session ID is an unique identification string usually a

long, random and alpha-numeric string. It is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages.

What is Session Tracking?


HTTP is stateless protocol and it does not maintain

the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time. Different types of Session Tracking? a) Cookies b) URL rewriting c) Hidden form fields d) SSL Sessions

Hidden form fields


<input type=hidden name=sessinID value=7546> Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session tracking. These fields are not visible directly to the user, but can be

viewed using view source option from the browsers. This type doesnt need any special configuration from the browser of server and by default available to use for session tracking. This cannot be used for session tracking when the conversation included static resources lik html pages.

URL Rewriting
Original URL: http://server:port/servlet/ServletName Rewritten URL: http://server:port/servlet/ServletName?sessionid=7546 When a request is made, additional parameter is appended with the

url. In general added additional parameter will be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesnt need any special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We need to keep track of the parameter as a chain link until the conversation completes and also should make sure that, the parameter doesnt clash with other application parameters.

Cookies

Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie along with it. Then the server can identify the client using the cookie. In java, following is the source code snippet to create a cookie: Cookie cookie = new Cookie(sessionID, 7546); response.addCookie(cookie); Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to disable cookies using their browser preferences. In such case, the browser will not save the cookie at client computer and session tracking fails.

Session tracking API


HttpServletRequest interface has a method to create

HttpSession object to track the session. HttpSession ses = request.getSession(true);


this method will check whether already a session is existing

for the user. If a session is existing, it will return that session object, Otherwise will create a session object expicitly and returns to the client.

HttpSession ses = request.getSession(); Alternate shortcut method for request.getSession(true) HttpSession ses = request.getSession(false); this method will check whether a session is existing. If yes, then it returns the reference of that session object, Otherwise it returns 'null'.

Creating the session

Setting a new attribute in session

ServletContext Scope
The context scope parameters are stored in web.xml

The context scope parameters are shared by all servlets

in the same web application

Context scope attributes

Redirect into another webpage


sendRedirect () method: This method is declared in HttpServletResponse

Interface. Signature: void sendRedirect(String url) This method is used to redirect client request to some other location for further processing ,the new location is available on different server or different context. Our web container handle this and transfer the request using browser ,and this request is visible in browser as a new request. Some time this is also called as client side redirect

Mechanism used by sendRedirct()

Using RequestDespacher
Forward() method: ( declared in RequestDispatcher Interface ) Signature: forward(ServletRequest request, ServletResponse response) This method is used to pass the request to another resource for further

processing within the same server, another resource could be any servlet, jsp page any kind of file. This process is taken care by web container. When we call forward method request is sent to another resource without the client being informed, which resource will handle the request it has been mention on requestDispatcher. We can get by two ways either using ServletContext or Request. This is also called server side redirect. RequestDispatcher rd = request.getRequestDispatcher("pathToResource"); rd.forward(request, response); Or RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource"); rd.forward(request, response);

Forward()
request is transfer to other resource within the same server. Web container handle all process internally and client or browser is not involved.

sendRedirect()
request is transfer to another resource to different domain or different server

container transfers the request to browser so url given inside the sendRedirect() is visible as a new request to the client. We pass request and response object so old request and response object is lost our old request object is present on new because its treated as new request by resource which is going to process our the browser. request faster then send redirect. SendRedirect is slower because completely new request is created and old request object is lost. We can use same data in new resource We cannot store the request scope data with request.setAttribute () as we have because the old request object is lost. request object available.

Example using forward()


Using sendRedirect() : On same server response.sendRedirect("http://localhost:8090/Chaining/Ch ain2"); On another server String name=request.getParameter("name"); response.sendRedirect("http://www.google.co.in/#q="+nam e); Using forward() request.getRequestDispatcher(/hello.jsp).forward(req,re

s)

Difference between the getRequestDispatcher() method of ServletContext and that of ServletRequest


You can pass a relative path to the getRequestDispatcher() method of

ServletRequest but not to the getRequestDispatcher() method of ServletContext. For example, request.getRequestDispatcher("../html/copyright.html") is valid, and the getRequestDispatcher() method of ServletRequest will evaluate the path relative to the path of the request. For the getRequestDispatcher() method of ServletContext, the path parameter cannot be relative and must start with /. This makes sense because ServletRequest has a current request path to evaluate the relative path while ServletContext does not. You cannot directly forward or include a request to a resource in another web application. To do this, you need to get a reference to the Servlet-Context of the other web application using this.getServletContext().getContext(uripath). Using this servlet context reference, you can retrieve an appropriate RequestDispatcher object as usual.

Cookies are text files stored on the client computer and

Cookies

they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies. There are three steps involved in identifying returning users:
Server script sends a set of cookies to the browser. For

example name, age, or identification number etc. Browser stores this information on local machine for future use. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.

The Anatomy of a Cookie


Cookies are usually set in an HTTP header .
A servlet that sets a cookie might send headers that

look something like this:

Setting Cookies with Servlet

Example :

Reading Cookies with Servlet


To read cookies, you need to create an array of

javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.

You might also like