Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
A session is time duration. It starts from the client’s conversation with the server and terminates at the end of it. The data we transfer from the client to the server through multiple requests during a particular session is known as the session’s state.
It is important to manage the client’s previous request when processing a request in web applications. A container prepares a request object when the request is received from the client, and it destroys the request object when the response is dispatched to the client.
Hence, it is not sufficient to manage the client’s previous requests. To represent a particular user, a separate session is prepared. To keep track of all the session’s objects at the server, we need to set an explicit mechanism known as Session Tracking Mechanism.
Session Tracking
Sometimes we need to transfer the data between multiple forms in our applications. However, in the form-based applications, we use HTTP protocol which is a stateless protocol that means it remembers only the current conversation. E.g., if we leave the first form and enter into the second form, we will forget about the previous form data.
To overcome this limitation and to transfer the data between multiple forms, we refer to the following methodologies:
Cookies
Hidden Variables
URL Rewriting
Session Object
These techniques allow clients to send a unique identifier with each request, which enables the server to determine the user session based on these unique identifiers.
Session Management is used to recognize a particular user. It is a way to maintain the user’s state about a series of requests from the same user (from the same browser) across the same period. Each time the user requests the server, the server treats the request as a new one.
Need of Session Tracking
When a client makes a request, a new connection is established to the webserver for each request. It becomes difficult for servers to identify whether the requests are coming from the same user or not. Also, the server does not keep track of the information of the previous request made by the user.
To overcome this problem, we need to maintain a unique id for every request that helps to maintain a complete conversation between the client and the server.
Cookies are used to transfer the data between multiple form-based applications. A cookie is a tiny piece of information sent by the server to the client—every cookie stores the data in the form of a key-value pair. The server adds the cookie to the response header by using the Set-Cookie header and sends the cookie to the client. Cookies are stored in the browser by using the website’s domain name. A browser can contain cookies from multiple domains. The client needs to use the HeaderCookie to get all the cookies available in the browser.
There are two types of cookies:
Session cookies - These cookies are temporary and are deleted as soon as the user closes the browser, after which, if the user visits the same website, the server treats it as a new client.
Persistent cookies - These cookies remain on the hard drive until the user deletes them or expires.
Syntax:
Cookie myCookie = new Cookie(“SessionID”, “SessionValue”)
Creating a Cookie:
Cookie cookie=new Cookie("client","Coding Ninjas"); //creating cookie object
response.addCookie(cookie); //adding cookie in the response
getComment (): This returns a comment describing the purpose of the cookie.
getMaxAge (): This returns the maximum specified age of the cookie.
getName() : This returns the name of the cookie.
getPath() : This returns the URL for which cookie is targeted.
getValue() : This returns the value of the cookie.
setComment(String): This comment is used to describe the cookie’s purpose.
setMaxAge(int): This is used to set the maximum age of the cookie. A zero value will cause a cookie to be deleted.
setPath(String): It determines the cookie should begin with this URL.
setValue(String): It is used to set the value of the cookie. Values with special characters should be avoided.
Advantages of cookies
Cookies are better to transfer the data as once the cookie is stored, the data can be accessed directly on any page of the website.
Disadvantages of cookies
If the client disables the cookies in the browser, the server will not identify the user.
Cookies are not recommended for security reasons.
It becomes complicated when a huge amount of data between the server and the client is required to share
Hidden Variables
We have to use the hidden fields given by HTML to use variables. These hidden fields must be specified as a part of the <form> and with the name and value attributes. These fields are not displayed to the client, but their value is sent as other input fields. When the form has been submitted, the name and the value fields are automatically included in the GET and the POST data. The value in the above example can be retrieved using a request.getParameter(“xxx”)
Syntax:
<input type=”hidden” name=”xxx” value=”CN”/>
Here, the name is the hidden field, and CN represents the hidden field value.
Advantages of hidden variables
The hidden variables consume less memory.
Once the browser is closed, the data of hidden variables clear automatically.
Disadvantages of hidden variables
It is complicated to carry a huge amount of data using hidden variables.
Hidden variables are not recommended to transfer sensitive data.
This approach cannot be used for static pages.
URL Rewriting
URL Rewriting is an approach in which a session ID gets appended with each request URL so the server can identify the user session.
By using a unique identifier, the server can easily identify the user. It is known as handling the browsers. When the user clicks on the new rewritten link, the servlet easily recognizes the SessionID.
Advantages of URL rewriting
There is no need to pass hidden values.
This method works even if the user has disabled cookies.
This technique is independent of the browser.
Disadvantages of URL rewriting
The client needs to append the sessionID and regenerate the URL with each request.
Also, the client needs to keep track of the unique ID until the conversation ends between the client and the server.
Session Object
The session object is a representation of a user session. User Session starts when a user opens the web browser and sends the first request to the server. The session object is available in the entire user session, so the attributes stored in the HTTP session will be available in a servlet or a JSP.
When a session is created, the server generates a unique ID and attaches that ID to the session. The server sends back this ID to the client, and then on, the browser sends back this ID with every request of that user to the server with which the server identifies the user.
To handle the session object explicitly, we have to write the following page re-directive in the JSP code:
<%@ page session=”false|true”%>
Advantages of Session object
The Session Object technique is more reliable as each user has its uniqueID, which is helpful to access the data stored at the server-side.
How to Get a Session Object
Calling the getSession() method on HttpServletRequest object.
a) HttpSession session = request.getSession()
b) HttpSession session = request.getSession(Boolean)
session.invalidate(): This method kills a user session and is used specifically when the user logs off.
Methods in Session Object
public Object getAttribute(String attributeName): This method is used to get the attribute stored in the session scope by an attribute name. The return type of this method is an Object.
public Enumeration getAttributeNames(): These methods return an enumeration of string objects containing the names of all the objects bound to that session.
public long getCreationTime(): This method returned when the session was created.
public string getId(): This method returns a string containing the identifier assigned to this session.
public long getLastAccessedTime(): This method returns the last time the client sent a request associated with this session.
public int getMaxInvalidateInterval(): This method returns the max time interval when the container keeps the session open.
public int setMaxInactiveInterval(): This method returns the time before the container will invalidate the session.
public void setAttribute(String attributeName, Object value): This method stores an attribute in the session scope.
public void removeAttribute(String attributeName): This method removes an attribute from a session.
public boolean isNew()- This method returns true if the server does not find any state of the client.
Given an example, we will try to use the invalidate method in the session.
session. invalidate() kills the corresponding server session. This API is used when a logged-in user logs out. Once the session is invalidated, a call on that server will throw an error.
Create a login.JSP page to take the username and password of the user.
Displaydetails.JSP will store the username in session and create a link, which will invoke the logout.JSP page.
The logout.JSP will call the session. invalidate() to kill the server session.
Accessing the session object after invalidating will throw an error.
Q1. Why can’t we use the ServletContext object to manage the client’s previous request?
Ans:The ServletContext object shares its data to all the components used in the current application and to all the application users. Due to this, the ServletContext object cannot provide a clear-cut separation between the multiple users.
Q2. How Browser session is different from Server Session?
Ans: To understand the difference between the Browser Session and the Server Session. Consider the following table:
Q3. Can we stop multiple submits to a web page that is initiated by clicking to refresh button?
Ans: Yes, it can be solved using a Post/Get/Redirect pattern.
A form gets submitted to the server using the POST or GET method.
The state in the database model is updated.
A redirect response is used to reply by the engine for a view page.
The browser loaded a view using the GET command, and no user’s data was sent.
This is safe from multiple submits as it is a separate JSP page.
Key Takeaways
This blog discussed session tracking and different techniques used in session tracking, with a few examples.
The data we transfer from the client to the server through multiple requests during a particular session is known as the session’s state.
The data we transfer from the client to the server through multiple requests during a particular session is known as the session’s state.
Session Management is used to recognize a particular user. It is a way to maintain the user’s state about a series of requests from the same user (from the same browser) across the same period.
Each time the user requests the server, the server treats the request as a new one.
If you are a beginner and interested in exploring other fields such as web development, core subjects, or competitive programming. In that case, you can follow our guided path to get a good grip on your concepts.