一、session介绍

Session用于保存服务端与客户端“会话”的信息。例如你逛淘宝时添加到购物车中的商品的信息就是保存到Session中。与Cookies不同的是,Session保存在服务端。每个客户端会有一个与之关联的Session,服务器会将Session的ID写到客户端的Cookies或者URL。如果客户端禁止Cookies了,服务器会将ID写到URL中。

二、Session实例

public class ShowSession extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Session Tracking Example";
//得到客户端对应的session对象,true表示如果在服务器端找不到对应的session对象则创建一个
//得到的是一个session引用,实现HttpSession的具体类
HttpSession session = request.getSession(true);
String heading;
// Use getAttribute instead of getValue in version 2.2.
//得到Session内,与accessCount名字所对应的值
     Integer accessCount = (Integer) session.getAttribute("accessCount");
if (accessCount == null) {
accessCount = new Integer(0);
heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
accessCount = new Integer(accessCount.intValue() + 1);
}
// Use setAttribute instead of putValue in version 2.2.
//像Session内放入对象,第一个参数作为key或者称之为名字,与Map差不多
session.setAttribute("accessCount", accessCount);
        out.println("<html><head><title>Session追踪</title></head>"
+ "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">"
+ heading + "</H1>\n"
+ "<H2>Information on Your Session:</H2>\n"
+ "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
+ "<TR BGCOLOR=\"#FFAD00\">\n" + " <TH>Info Type<TH>Value\n"
+ "<TR>\n" + " <TD>ID\n" + " <TD>" + session.getId() + "\n"
+ "<TR>\n" + " <TD>Creation Time\n" + " <TD>"
//表示Session对象的创建时间
+ new Date(session.getCreationTime()) + "\n" + "<TR>\n"
+ " <TD>Time of Last Access\n" + " <TD>"
//最后一次访问时间
+ new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n"
+ " <TD>Number of Previous Accesses\n" + " <TD>"
+ accessCount + "\n" + "</TABLE>\n" + "</BODY></HTML>");
}

三、第二个Seesion实例

public class SessionInfoServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException{
HttpSession mySession = request.getSession(true);
response.setContentType("text/html");
//response表示服务端的回应
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Session Info Servlet</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<H3>Session Information</H3>");
//判断Session是否创建
out.println("New Session: " + mySession.isNew());
//得到Session的ID
out.println("<BR>Session ID: " + mySession.getId());
out.println("<BR>Session Creation Time: " +
new java.util.Date(mySession.getCreationTime()));
out.println("<BR>Session Last Accessed Time: " +
new java.util.Date(mySession.getLastAccessedTime())); out.println("<H3>Request Information</H3>");
out.println("Session ID from Request: " +
//request代表客户端的请求,获得从客户端带来的ID
request.getRequestedSessionId());
out.println("<BR>Session ID via Cookie: " +
//判断ID号是否从Cookie内取出来的
request.isRequestedSessionIdFromCookie());
out.println("<BR>Session ID via rewritten URL: " +
//判断ID号是否从URL内取出来的
request.isRequestedSessionIdFromURL());
out.println("<BR>Valid Session ID: " +
//判断从客户端取出的ID是否合法
request.isRequestedSessionIdValid());
out.println("</BODY></HTML>");
out.close(); //close output stream
}

四、Session URL重写

public class URLSession extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); out.println("<html><head><title>Session追踪</title></head>"
+ "<BODY>\n"
+ "session id:" + session.getId() + "</br>"
+ "from url:" + request.isRequestedSessionIdFromURL() + "</br>"
+ "from cookie:" + request.isRequestedSessionIdFromCookie() + "</br>"
//URL重写
+ "<a href=" + response.encodeURL(request.getRequestURL().toString())
             + ">test</a> </br>"
//得到当前访问的Session地址
+ "<a href=" + request.getRequestURI().toString() + ">test</a>"
+ "</BODY></HTML>"); }

五、Session总结

Session是服务器端的一块内存

Session与客户端窗口对应,只要客户端窗口不关就可以访问到,默认失效时间30m,在Tomacat的conf文件夹下的web.xml文件中配置。

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>

客户端与服务器有对应的SessionID

客户端向服务器端发送SessionID的时候有两种方式:

    1、Cookie

    2、重写URL

Servlet session的更多相关文章

  1. JavaWeb学习记录总结(二十九)--Servlet\Session\Cookie\Filter实现自动登录和记住密码

    一.Servlet package autologin.servlet.login; import java.io.IOException;import java.security.MessageDi ...

  2. jsp&servlet——session监听

    session监听,需要实现HttpSessionAttributeListener接口 attributeAdded:监听添加session attributeRemoved:监听删除session ...

  3. Servlet Session 跟踪

    HTTP 是一种"无状态"协议,这意味着每次客户端检索网页时,客户端打开一个单独的连接到 Web 服务器,服务器会自动不保留之前客户端请求的任何记录. 但是仍然有以下三种方式来维持 ...

  4. Servlet session的理解

    servlet参见http://blog.csdn.net/bryanliu1982/article/details/5214899 session参见http://lavasoft.blog.51c ...

  5. Servlet Session MVC模式

    一   什么是Session 当首次使用session时,服务器端要创建session,session是保存在服务器端,而给客户端的session的id(一个cookie中保存了sessionId). ...

  6. Servlet Session的使用

    Session 是服务器端会话技术.当浏览器访问 Web 服务器的资源时,服务器可以为每个用户浏览器创建一个 Session 对象,每个浏览器独占一个 Session 对象.由于每个浏览器独占一个 S ...

  7. servlet session 相关

    1.session是server维护的一个变量,如果消除每个session?----这里只做指定key的session删除 1.1.显示调用 废除指定key的session session.remov ...

  8. 在报表中给session赋值实现报表间参数共享

    1. 问题描述 在报表开发工具FineReport中,若有几张不同的报表,每张报表都有一个共同的项可以选择,比如日期时间.我们希望选择了第一张报表的时间之后,其他报表的默认时间都变为第一张报表选择的时 ...

  9. Using Sessions and Session Persistence---reference

    Using Sessions and Session Persistence The following sections describe how to set up and use session ...

随机推荐

  1. Java基础知识笔记(三:文件与数据流)

    一.输入流与输出流 输入流将数据从文件.标准输入或其他外部输入设备中加载到内存.输出流的作用则刚好相反,即将在内存中的数据保存到文件中,或传输给输出设备.输入流在Java语言中对应于抽象类java.i ...

  2. ASP.NET MVC 5 with EF 6 上传文件

        参考   ASP.NET MVC 5 with EF 6 - Working With Files Rename, Resize, Upload Image (ASP.NET MVC) ASP ...

  3. CH Round #52 还教室[线段树 方差]

    还教室 CH Round #52 - Thinking Bear #1 (NOIP模拟赛) [引子]还记得 NOIP 2012 提高组 Day2 中的借教室吗?时光飞逝,光阴荏苒,两年过去了,曾经借教 ...

  4. [转载]彻底弄清struct和typedef struct

    struct和typedef struct 分三块来讲述: 1 首先://注意在C和C++里不同 在C中定义一个结构体类型要用typedef: typedef struct Student { int ...

  5. Binder理解

    native takepicture -> camera -> ICamera: class bpbinder: transact -> BpBinder: transact -&g ...

  6. c#读写txt

    附加到txt:StreamWriter sw =System.IO.File.AppendText(path); //绝对路径 sw.Write("写入内容"); 写入到txt: ...

  7. CSS让图片垂直居中的几种技巧

    在网页设计过程中,有时候会希望图片垂直居中的情况.而且,需要垂直居中的图片的高度也不确定,这就会给页面的布局带来一定的挑战.下面总结了一下,曾经使用过的几种方法来使图片垂直居中,除了第一种方法只限于标 ...

  8. Android5.0资源 colorAccent,colorPrimary,colorPrimaryDark

  9. 《DOM Scripting》 - 阅读笔记

    DOM Scripting - Web Design with JavaScript and the Document Object Model,Jeremy Keith中文名:JavaScript ...

  10. Jquery揭秘系列:Validation实现

    之前讲了一部分揭秘系列的东西,由于年初的时候在改项目,也没有写下去.现在开始闲下来了,会继续写没写完的东西,各种原生js实现Jquery的功能. 转入正题,说一下今天要讲的东西. 相信很多tx在项目里 ...