Updated April 3, 2023
Introduction to Session in Servlet
In a dynamic web, the application servlet is one of the controllers in the back end for the web MVC design model. For each client request, the server response will be received as a client for any front end programming techniques like jsp, HTML, etc. Here server is servlet for sending a response to the particular request in front end view. We can save the user request and response-related data stored in logs as well as servlet techniques like session. The session is mainly used for time duration for the client and server interactions. We can track the data using session tracking to maintain the user data in a particular state.
Syntax:
Given below is the basic syntax of servlet sessions:
import javax.servlet.*;
import javax.servlet.http.*;
class classname extends HttpServlet
{
public void doGet(HttpServletRequest request ,HttpServletResponse response)
{
----some logic codes—
HttpSession instance=request.getSession();
}
public void doPost(HttpServletRequest request ,HttpServletResponse response)
{
----some logic codes—
HttpSession instance=request.getSession();
}
}
The above codes are the servlet http session codes for handling the user sessions and also managed the application’s data in browser cookies.
How to use Session in Servlet?
- When we use the same session instance in the jsp it may have some advantages when compared to servlet default session management is enabled in jsp but it explicitly enabled in servlet. In web-based application session is indicated at some period duration for the single user used in that application session is started whenever the user visits the index page of the application. After that user will visit and navigate the other pages in all the data to be recorded in the sessions. Once the user has got the session timeout error or any server related errors the session is stopped and it throws some validated errors.
- In java the http protocol is used for handling the sessions in applications http is stateless and also it’s helpful for handling the sessions through cookies, URL rewriting or hidden for field techniques is used to identify all the different requests in a single user. Using session tracking techniques is the primary for handling cookies. If suppose user browser does not support cookies then it will proceed with other techniques like url rewriting etc. In web developers used the session mechanism for user data in the particular state as well as time duration, such as registered users authentication, usernames, or any other related data that needs to be shared with the whole requests.
- Using httpsession object it will represent the whole sessions for the single user. httpsession is the interface that is defined in the package called javax.servlet. The implementation is handled by the user httpservlet request by the servlet containers. We can store the user-related data in the key-value pairs which is already in the java collection interface called map which is defined as class like hashmap. The httpsession interface calls methods like setAttribute (key, value) is storing while retrieving getAttribute(key) is used to retrieve the particular key. In default, java language use cookies for handling the session tracking the cookie with name called JSESSIONID is used for stored in the web browsers. It is also used for handling different requests with the same user.
Examples of Session in Servlet
Given below are the examples of Session in Servlet:
Example #1
Html Code:
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
</head>
<body>
<form action="//second.java">
<input type="text" placeholder="Name" name="name"><br><br>
<input type="text" placeholder="City" name="city"><br><br>
<input type="submit" value="submit"><br>
</form>
</body>
</html>
Java Code:
package com.first;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class second
*/
@WebServlet("/second")
public class second extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @seeHttpServlet#HttpServlet()
*/
public second() {
super();
// TODO Auto-generated constructor stub
}
/**
* @seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
Protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
request.getRequestDispatcher("index.html").include(request, response);
String name = request.getParameter("name");
String city = request.getParameter("city");
out.print("Welcome, "+name);
HttpSessionsession=request.getSession();
session.setAttribute("name",name);
out.close();
}
/**
* @seeHttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
Protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Output:
Example #2
Java Code:
package com.first;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class sessions extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
Date startdate = new Date(session.getCreationTime());
Date lastdate = new Date(session.getLastAccessedTime());
String s = "Welcome Back to my domain";
Integer i = new Integer(0);
String v = new String("lasytvisittimes");
String u = new String("id");
String u1 = new String("welcome");
if (session.isNew() ){
s = "Welcome to my domain";
session.setAttribute(u, u1);
session.setAttribute(v, i);
}
i = (Integer)session.getAttribute(v);
v = v + 1;
u1 = (String)session.getAttribute(u);
session.setAttribute(v, i);
response.setContentType("text/html");
PrintWriterout = response.getWriter();
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + s + "</title></head>\n" +
"<body bgcolor = \"green\">\n" +
"<h1 align = \"center\">" + s + "</h1>\n" +
"<h2 align = \"center\">SessionInfomations</h2>\n" +
"<table border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"green\">\n" +
" <th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>sessionid</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>SessionCreationTime</td>\n" +
" <td>" + startdate + " </td></tr>\n" +
"<tr>\n" +
" <td>SessionLastCreated</td>\n" +
" <td>" + lastdate + " </td></tr>\n" +
"<tr>\n" +
" <td>UserID</td>\n" +
" <td>" + u1 + " </td></tr>\n" +
"<tr>\n" +
" <td>NumberofUsers</td>\n" +
" <td>" + i + "</td></tr>\n" +
"</table>\n" +
"</body></html>"
);
}
}
Output:
Example #3
Java Code:
public class second extends HttpServlet {
private static final long serialVersionUID = 1;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user = request.getParameter("name");
String email = request.getParameter("email");
String city = request.getParameter("city");
out.println("<HTML>");
out.println("<h2>your name is :"+user+"</h2>");
out.println("<h2>your email is :"+email+"</h2>");
out.println("<h2>your city is :"+city+"</h2>");
out.println("</HTML>");
out.flush();
out.close();
}
}
Output:
Conclusion
In the servlet session, handling mechanism helps for tracking the user-related information in the web applications, and also it has their own configurations compared to jsp config we have specified it in config files like web.xml, etc.
Recommended Articles
This is a guide to Session in Servlet. Here we discuss the introduction, how to use session in servlet, configurations compared to jsp config with various examples. You may also have a look at the following articles to learn more –