Today, I gained insight into a very important concept of session tracking in servlet. Session Tracking is a way to maintain state (data) of a user to recognize the user. It becomes very important to persist the data of user while the user is navigating between different web pages.
We have four techniques to do the same:
- Cookies
- URL Rewriting
- Hidden Form Fields
- HttpSession
- Cookies:
Cookies are key-value pairs consisting of user’s information or other important information that are stored in cache of browser. When client makes request to the same site, cookies stored during the last session will be transferred along the request, so that the site recognizes the user as an old user and displays the content specific to the user.
Note: The value can only be of String type in cookies.
ServletClass(where cookies are created)-
@WebServlet("/Login")
public class ServletClass extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */
Cookie c1 = new Cookie("keyEmail", email);
Cookie c2 = new Cookie("keyAge", String.valueOf(age));
Cookie c3 = new Cookie("keySalary", String.valueOf(salary));
response.addCookie(c1);
response.addCookie(c2);
response.addCookie(c3);
PrintWriter out = response.getWriter();
out.print("<a href='Home'>Go to Home</a>");
}
}
ServletHome(where cookies are retrieved)-
@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<html><body>");
out.print("
<h3>Welcome User</h3>
");
//Getting the cookies
Cookie[] cookieArr = request.getCookies();
for(Cookie c: cookieArr)
out.print(c.getName()+" : "+c.getValue());
out.print("</body></html>");
}
}
We have some drawbacks of using cookies-
- It may be the case that cookies are disabled on client’s machine.
- We can’t get access to single cookie if we wish to access only one, rather we need to fetch the entire cookies array.
- URL Rewriting:
URL Rewriting embeds the the data in the form of key-value pair in the URL itself (to whichever page we are redirecting). ‘?’ is added after file name in URL. key and value is separated by ‘=’. One parameter is separated from another by ‘&’.
If you will observe, it’s nothing but a GET request in which data is shown in URL.
ServletClass(where URL is written)-
@WebServlet("/Login")
public class ServletClass extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */
PrintWriter out = response.getWriter();
out.print("<a href='Home?txtEmail="+email+"&txtAge=" + age +"&txtSalary="+salary+"'>Go to Home page</a>");
}
}
ServletHome(where data is fetched from URL)-
@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("txtEmail");
int age = Integer.parseInt(request.getParameter("txtAge"));
int salary= Integer.parseInt(request.getParameter("txtSalary"));
out.println("Email : "+email);
out.println("Age : "+age);
out.println("Salary : "+salary);
}
}
This method has drawbacks:
- Sensitive data can’t be transferred using this technique as data is visible in URL.
- Large amount of data has difficulty to be added in single URL.
- Hidden Form Fields:
In this technique, we store the information in the hidden field and get it from another servlet. We keep the type of input element as ‘hidden’.
ServletClass(where Hidden fields are created)-
@WebServlet("/Login")
public class ServletClass extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */
PrintWriter out = response.getWriter();
out.print("<html><body>");
out.print("
<form action='Home' method='post'>");
out.print("<input type='hidden' name='txtEmail' value='"+email+"'>");
out.print("<input type='hidden' name='txtAge' value='"+age+"'>");
out.print("<input type='hidden' name='txtSalary' value='"+salary+"'>");
out.print("<input type='submit' value='Go to Home Page'>");
out.print("</form>
</body></html>");
}
}
ServletHome(where data is fetched from Hidden fields)-
@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("txtEmail");
int age = Integer.parseInt(request.getParameter("txtAge"));
int salary = Integer.parseInt(request.getParameter("txtSalary"));
out.println("Email : "+email);
out.println("Age : "+age);
out.println("Salary : "+salary);
}
}
It has drawaback–
If we click View Page Source on that page, all the data will be revealed which we have kept hidden. So, privacy is difficult to maintain. :0
- HttpSession:
In this technique, container creates a session ID for each user. This ID is unique to user and will be used to identify particular user.
ServletClass(where Hidden fields are created)-
@WebServlet("/Login")
public class ServletClass extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */
HttpSession session = request.getSession();
session.setAttribute("keyEmail", email);
session.setAttribute("keyAge", age);
session.setAttribute("keySalary", salary);
out.print("<a href='Home'>Go to Home</a>");
}
}
ServletHome(where data is fetched from Hidden fields)-
@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String email = (String)session.getAttribute("keyEmail");
int age = (int)session.getAttribute("keyAge");
int salary = (int)session.getAttribute("keySalary");
out.print("Email : "+email+"
");
out.print("Age : "+age+"
");
out.print("Salary : "+salary+"
");
}
}