这是我的servlet,它创建会话并将accessCount存储到当前会话
@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);
}
}
这是打印出该会话内容的视图
<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>
问题在于即使我已经访问了很多次,它仍然会返回一个accessCount == 0,
我在localhost访问:8080 / someFolderName / ShowSession.do
答案 0 :(得分:1)
您从请求中获得了accessCount
初始值。你应该从会议中查看。
//Bad!
Integer accessCount = (Integer)request.getAttribute("accessCount");
//Good (maybe)
Integer accessCount = (Integer)session.getAttribute("accessCount");