会话跟踪?

时间:2012-08-31 15:08:04

标签: jsp servlets

我是java servlet的新手,实际上是在学习阶段..我面临着将JSP页面字段值发送到另一个页面的困难,这个页面在会话维护中遇到问题。请帮助我获得价值整个会议通过使用简单的建设性示例给出一些想法,以便很好地理解会话的使用..

提前致谢:)

1 个答案:

答案 0 :(得分:0)

以下是演示会话跟踪机制的JSP。尝试点击页面上的链接,在浏览器中启用和不启用Cookie。您应该能够通过使用cookie或编码URL来维护会话。在Chrome中轻松停用会话Cookie。

<%
  String servletPath = request.getServletPath();
  String contextPath = request.getContextPath();
  String path = contextPath + servletPath;
  String encoded = response.encodeURL(path);
  Integer count = (Integer)session.getAttribute("count");
  if(count==null)count = new Integer(0);
  session.setAttribute("count",new Integer(count.intValue() + 1));
%>
sessionId=<%=session.getId()%><br/>
isNew=<%=session.isNew()%><br/>
fromURL=<%=request.isRequestedSessionIdFromURL()%><br/>
fromCookie=<%=request.isRequestedSessionIdFromCookie()%><br/>
path=<%=path%><br/>
encoded=<%=encoded%><br/>
<a href="<%=path%>">Not encoded request</a><br/>
<a href="<%=encoded%>">Encoded request</a><br/>
count=<%=count%> 

上述页面适用于任何JSP容器。如果您使用新的(我使用Apache Tomcat / 7.0.28测试过),那么您可以使用以下页面。

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="count" value="${count + 1}" scope="session" />
<c:set var="relativePath" value="${fn:substringAfter(pageContext.request.servletPath, '/')}" />
The session id is ${pageContext.session.id}<br/>
Is the session new ? ${pageContext.session['new']}<br/>
Did the client send the session id in the URL ?   ${pageContext.request.requestedSessionIdFromURL}<br/>
Did the client send the session id in a cookie ?   ${pageContext.request.requestedSessionIdFromCookie}<br/>
<a href="${relativePath}">Not encoded request</a><br/>
<a href="${pageContext.response.encodeURL(relativePath)}">Encoded request</a><br/>
Count is ${count}