Distributed Session Sample

I wanted to see how the distributed Session works so i created this DistributeSessionSample.war file. This Web Application has a simple DistributedSessionSample servlet like this


public class DistributeSessionSample extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Entering DistributeSessionSample.doGet()");
HttpSession httpSession = request.getSession();
System.out.println("HttpSession Object " + httpSession);
String serverName = (String)httpSession.getAttribute("serverName");
System.out.println("Server Name " + serverName);
if(serverName == null){
System.out.println("Server Name is empty. Adding data to HttpSession");
serverName = ServerName.getDisplayName() + new Date();
httpSession.setAttribute("serverName", serverName);
}
response.setContentType("text/html");
response.getWriter().println("Server Name from Http Session " + serverName +"
");
response.getWriter().println("Server Display Name " + ServerName.getDisplayName() +"
");
response.getWriter().println("Server Full Name " + ServerName.getFullName() +"
");
response.getWriter().println("Server Id " + ServerName.getServerId() +"
");
System.out.println("Exiting DistributeSessionSample.doGet()");
}

}



In this servlet first i retrieve object of HttpSession from the current request. Then i check if it has serverName, if yes then retrieve its value and print it in output if not read name of the server that is handling current request and put it in session.

On my local machine i do have a cluster that has 2 servers, i deployed this application on my cluster and then i tried hitting the DistributedSessionSample from first server directly and i got this response.




Then i changed URL so that the request goes to Server 2 and while sending request to Server 2 it will send the JSESSIONID cookie based on that cookie server2 should be able to retrieve session object and retrieve the name of the server stored in the HttpSession. This is the output that i get on second server

No comments: