Java Session
Session indicates interval of time. A session is a simple time interval in which servers and client interacts. To maintain the state of the client or user we use technologies that implement session tracking. The main use of session tracking is to maintain the state of the users.
Session Tracking Techniques
There are 4 ways to track the sessions
- HTTP Session Interface
- Cookies
- Hidden from field
- URL rewriting
1. HTTP Session Interface
In HTTP interface, session id is created by taking the help of container for each user.
The objects which are created in this session can bind the objects and manipulate the session properties.
Methods in HTTP Session Interface
- public HttpSession getSession()
By using this method, we can get the information about current session. If there is no session, then a session will be created. - public String getId()
By using this method, a string is returned which contains the unique value. - public void invalidate ()
By using this method, it invalidates the session and unbinds the binded objects to it. - public long getCreationTime()
By using this method, we will get the time at which session is created and it is measured in milliseconds. - public long getLastAccessedTime()
By using this method, we will get to know the last time at which session is accessed and it is measured in milliseconds.
Program for servlets using HTTP session interface
index.html
<html>
<head>
<body>
<form action = "servletA">
UserName: <input type = "text" sername = "userName"/><br/>
<input type = "submit" value = "Press the Button"/>
</form>
</body>
</html>
ServletEx1.java
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class ServletEx1 extends HttpServlet {
public void Get(HttpServletRequest req, HttpServletResponse res)
{
try {
String conType = "text/html";
res.setContentType(conType);
PrintWriter oa = res.getWriter();
String sername = req.getParameter("userName");
oa.println("Welcome to Java" + sername + "!");
HttpSession httpSes= req.getSession();
httpSes.setAttribute("uname", sername);
oa.print("<a href='servletB'> Press Here </a>");
oa.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
ServletEx2.java
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class ServletEx2 extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
{
try
{
String conType = "text/html";
response.setContentType(conType);
PrintWriter oa = res.getWriter();
HttpSession se1 = req.getSession(false);
String name = (String)se1.getAttribute("uname");
// printing the name and message
oa.print(sername + " you have reached the second page.");
oa.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Web.xml
</textarea></div>
<p><strong>FileName:</strong> web.xml</p>
<div class="codeblock"><textarea name="code" class="xml">
<web-app >
<servlet >
<servlet-name > a1 </servlet-name >
<servlet-class > ServletEx1 </servlet-class >
</servlet >
<servlet-mapping >
<servlet-name > a1 </servlet-name >
<url-pattern > /servletA </url-pattern >
</servlet-mapping >
<servlet >
<servlet-name > a2 </servlet-name >
<servlet-class > ServletEx2 </servlet-class >
</servlet >
<servlet-mapping >
<servlet-name > a2 </servlet-name >
<url-pattern > /servletB </url-pattern >
</servlet-mapping >
</web-app >
2.Cookies in Servlet
Cookie consists of small information of multi-client requests. In the cookies approach, we include a cookie with the servlet response. Cookies are therefore kept in the browser's cache. After that, if the user sends a request, a cookie is automatically attached to the request.
Types of Cookies
- Non persistent Cookie
It is valid only for certain amount of time. Each time after the browser is closed, it is removed. - Persistent Cookie
It is valid for multiple sessions. It is replaced only if the user log out or sign out.
3.URL Rewriting
In this method we will append the previous identifier to next servlet. An approach of adding a session ID to the requested URL is called URL rewriting.
Program for servlets using URL rewriting
index.html
<html>
<head>
<body>
<form action = "servletA">
UserName: <input type = "text" sername = "userName"/><br/>
<input type = "submit" value = "Press the Button"/>
</form>
</body>
</html>
ServletEx1.java
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class ServletEx1 extends HttpServlet {
public void Get(HttpServletRequest req, HttpServletResponse res)
{
try {
String conType = "text/html";
res.setContentType(conType);
PrintWriter oa = res.getWriter();
String sername = req.getParameter("userName");
oa.println("Welcome to Java" + sername + "!");
HttpSession httpSes= req.getSession();
httpSes.setAttribute("uname", sername);
oa.print("<a href='servletB'> Press Here </a>");
oa.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
ServletEx2.java
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class ServletEx2 extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
{
try
{
String conType = "text/html";
response.setContentType(conType);
PrintWriter oa = res.getWriter();
HttpSession se1 = req.getSession(false);
String name = (String)se1.getAttribute("uname");
// printing the name and message
oa.print(sername + " you have reached the second page.");
oa.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Web.xml
</textarea></div>
<p><strong>FileName:</strong> web.xml</p>
<div class="codeblock"><textarea name="code" class="xml">
<web-app >
<servlet >
<servlet-name > a1 </servlet-name >
<servlet-class > ServletEx1 </servlet-class >
</servlet >
<servlet-mapping >
<servlet-name > a1 </servlet-name >
<url-pattern > /servletA </url-pattern >
</servlet-mapping >
<servlet >
<servlet-name > a2 </servlet-name >
<servlet-class > ServletEx2 </servlet-class >
</servlet >
<servlet-mapping >
<servlet-name > a2 </servlet-name >
<url-pattern > /servletB </url-pattern >
</servlet-mapping >
</web-app >
4.Hidden from field
In the case of a hidden form field, a hidden textfield is utilised to keep track of a user's status.
In this instance, the data is obtained from another servlet and stored in the hidden field. This strategy is preferable if we need to submit forms on each page and don't want to rely on the browser.