This is my servlet that creates the session and stores an accessCount to that current session
@WebServlet("/ShowSession.do")
public class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
String header;
Integer accessCount = (Integer)request.getAttribute("accessCount");
if(accessCount == null){
accessCount = new Integer(0);
header = "Welcome New Comer";
}else{
header = "Welcome Back!";
accessCount = new Integer(accessCount.intValue() + 1 );
}
//Integer is immutable data structure. so we cannot
//modify the old one in-place,Instead, you have to
//allocate a new one and redo setAttribute
session.setAttribute("accessCount", accessCount);
session.setAttribute("heading", header);
RequestDispatcher view = getServletContext().getRequestDispatcher("/showsession.jsp");
view.forward(request, response);
}
}
And this is the View that prints out the contents of that session
<body>
<%
HttpSession clientSession = request.getSession();
String heading = (String) clientSession.getAttribute("heading");
Integer accessCount = (Integer) clientSession
.getAttribute("accessCount");
%>
<h1>
<center>
<b><%=heading%></b>
</center>
</h1>
<table>
<tr>
<th>Info type</th>
<th>Value</th>
<tr>
<tr>
<td>ID</td>
<td><%=clientSession.getId()%></td>
</tr>
<tr>
<td>Creation Time</td>
<td><%=new Date(clientSession.getCreationTime())%></td>
</tr>
<tr>
<td>Time of last Access</td>
<td><%=new Date(clientSession.getLastAccessedTime())%></td>
</tr>
<tr>
<td>Number OF Access</td>
<td><%=accessCount%></td>
</tr>
</table>
</body>
THe problem is that even though I already access for a lot of times it still returns me an accessCount == 0,
I am accessing at localhost:8080/someFolderName/ShowSession.do
You’re getting your
accessCountinitial value from the request. You should check it from session.