您的位置:首页 > 其它

servlet学习笔记--如何追踪session

2015-04-02 17:08 330 查看
// 如果不存在 session 会话,则创建一个 session 对象

HttpSession session = request.getSession(true);

// 获取 session 创建时间

Date createTime = new Date(session.getCreationTime());

// 获取该网页的最后一次访问时间

Date lastAccessTime =

new Date(session.getLastAccessedTime());

String title = "欢迎回到我的网站";

Integer visitCount = new Integer(0);

String visitCountKey = new String("visitCount");

String userIDKey = new String("userID");

String userID = new String("ABCD");

// 检查网页上是否有新的访问者

if (session.isNew()){

title = "欢迎来到我的网站";

session.setAttribute(userIDKey, userID);

} else {

visitCount = (Integer)session.getAttribute(visitCountKey);

visitCount = visitCount + 1; //记录当前登录者的访问次数

userID = (String)session.getAttribute(userIDKey);

}

session.setAttribute(visitCountKey, visitCount);

// 设置响应内容类型

response.setCharacterEncoding("utf-8"); //设置编码格式

response.setContentType("text/html;charset=utf-8");

PrintWriter out = response.getWriter();

String docType =

"<!doctype html public \"-//w3c//dtd html 4.0 " +

"transitional//en\">\n";

out.println(docType +

"<html>\n" +

"<head><title>" + title + "</title></head>\n" +

"<body bgcolor=\"#f0f0f0\">\n" +

"<h1 align=\"center\">" + title + "</h1>\n" +

"<h2 align=\"center\">Session 信息</h2>\n" +

"<table border=\"1\" align=\"center\">\n" +

"<tr bgcolor=\"#949494\">\n" +

" <th>Session 信息</th><th>值</th></tr>\n" +

"<tr>\n" +

" <td>id</td>\n" +

" <td>" + session.getId() + "</td></tr>\n" +

"<tr>\n" +

" <td>Creation Time</td>\n" +

" <td>" + createTime +

" </td></tr>\n" +

"<tr>\n" +

" <td>Time of Last Access</td>\n" +

" <td>" + lastAccessTime +

" </td></tr>\n" +

"<tr>\n" +

" <td>User ID</td>\n" +

" <td>" + userID +

" </td></tr>\n" +

"<tr>\n" +

" <td>Number of visits</td>\n" +

" <td>" + visitCount + "</td></tr>\n" +

"</table>\n" +

"</body></html>");

=========================================================

移除一个特定的属性:您可以调用 public void removeAttribute(String name) 方法来删除与特定的键相关联的值。 to delete the value associated with a particular key.
删除整个 session 会话:您可以调用 public void invalidate() 方法来丢弃整个 session 会话。
设置 session 会话过期时间:您可以调用 public void setMaxInactiveInterval(int interval) 方法来单独设置 session 会话超时。
注销用户:如果使用的是支持 servlet 2.4 的服务器,您可以调用 logout 来注销 Web 服务器的客户端,并把属于所有用户的所有 session 会话设置为无效。
web.xml 配置:如果您使用的是 Tomcat,除了上述方法,您还可以在 web.xml 文件中配置 session 会话超时,如下所示:

<session-config>
    <session-timeout>15</session-timeout>
  </session-config>


上面实例中的超时时间是以分钟为单位,将覆盖 Tomcat 中默认的 30 分钟超时时间。

在一个 Servlet 中的 getMaxInactiveInterval() 方法会返回 session 会话的超时时间,以秒为单位。所以,如果在 web.xml 中配置 session 会话超时时间为 15 分钟,那么 getMaxInactiveInterval()
会返回 900。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐