Servlet session

    一、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

posted @ 2013-07-13 16:07  薛遗山  阅读(532)  评论(0编辑  收藏  举报