当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

Session and Cookies 2

发表于: 2013-10-23   作者:Capfish   来源:转载   浏览次数:
摘要: 转载自:http://www.java-programming.info/tutorial/pdf/csajsp2/08-Session-Tracking.pdf http://www.java2s.com/Code/Java/Servlets/Usecookietosavesessiondata.htm Session Tracking   HttpSession session

转载自:http://www.java-programming.info/tutorial/pdf/csajsp2/08-Session-Tracking.pdf

http://www.java2s.com/Code/Java/Servlets/Usecookietosavesessiondata.htm

Session Tracking

 

HttpSession session = request.getSession();
synchronized(session) {
SomeClass value =
(SomeClass)session.getAttribute("someID");
if (value == null) { 
value = new SomeClass(...);
}
doSomethingWith(value);
session.setAttribute("someID", value);
}

 

  •  The J2EE blueprints say not to bother
    • There are no race conditions when multiple different users access the page simultaneously
    • On the face of it, it seems practically impossible for the same user to access the session concurrently
  • The rise of Ajax makes synchronization mportant
    • With Ajax calls, it is actually quite likely that two requests from the same user could arrive concurrently
  • Performance tip
    • Don’t do “synchronized(this)”!
      • Use the session or perhaps the value from the session as the label of the synchronized block

 

      HttpSession Methods:

  • getAttribute

    Extracts a previously stored value from a session object. Returns null if no value is associated with given name.

  • setAttribute
    Associates a value with a name. Monitor changes: values 

    implement HttpSessionBindingListener.

  • removeAttribute
    Removes values associated with name.
  • getAttributeNames
    Returns names of all attributes in the session.
  • getId
    Returns the unique identifier.

  • isNew
    Determines if session is new to client (not to page)

  • getCreationTime
    Returns time at which session was first created
  • getLastAccessedTime
    Returns time at which session was last sent from client
  • getMaxInactiveInterval, setMaxInactiveInterval

    Gets or sets the amount of time session should go without access before being invalidated

  • invalidate
    Invalidates current session

Use cookie to save session data:

 

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShoppingCartViewerCookie extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    String sessionid = null;
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("sessionid")) {
          sessionid = cookies[i].getValue();
          break;
        }
      }
    }

    // If the session ID wasn't sent, generate one.
    // Then be sure to send it to the client with the response.
    if (sessionid == null) {
      sessionid = generateSessionId();
      Cookie c = new Cookie("sessionid", sessionid);
      res.addCookie(c);
    }

    out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");
    out.println("<BODY>");

    // Cart items are associated with the session ID
    String[] items = getItemsFromCart(sessionid);

    // Print the current cart items.
    out.println("You currently have the following items in your cart:<BR>");
    if (items == null) {
      out.println("<B>None</B>");
    } else {
      out.println("<UL>");
      for (int i = 0; i < items.length; i++) {
        out.println("<LI>" + items[i]);
      }
      out.println("</UL>");
    }

    // Ask if they want to add more items or check out.
    out.println("<FORM ACTION=\"/servlet/ShoppingCart\" METHOD=POST>");
    out.println("Would you like to<BR>");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");
    out.println("</FORM>");

    // Offer a help page.
    out.println("For help, click <A HREF=\"/servlet/Help"
        + "?topic=ShoppingCartViewerCookie\">here</A>");

    out.println("</BODY></HTML>");
  }

  private static String generateSessionId() throws UnsupportedEncodingException {
    String uid = new java.rmi.server.UID().toString(); // guaranteed unique
    return URLEncoder.encode(uid,"UTF-8"); // encode any special chars
  }

  private static String[] getItemsFromCart(String sessionid) {
    return new String[]{"a","b"};  
  }
}

 

Session and Cookies 2

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
网上有很多关于cookies和session的资料和讨论,但是基本上没有能形象的、系统的、完善的说清楚这两
session、cookies和application的区别 初学WEB对常见的几个东西做一个小区别总结 之上几者的主要区
众所周知,客户端使用Cookies来保存用户数据的,服务端用Session来保存用户数据~ Cookies的设计应该
Asp.Net里的Cookies 什么是cookies Cookies有很多种,网站上的cookie,浏览器的cookie,会话cookie
设置session和cookies的代码(webform1.aspx) if (txtName.Text == "wlzcool") { Session["uid"] =
参考资料 1 Frameset导致Cookies和Session丢失的原因及解决办法 http://blog.csdn.net/zl_c/article/
参考资料 1 Frameset导致Cookies和Session丢失的原因及解决办法 http://blog.csdn.net/zl_c/article/
参考资料 1 Frameset导致Cookies和Session丢失的原因及解决办法 http://blog.csdn.net/zl_c/article/
参考资料 1 Frameset导致Cookies和Session丢失的原因及解决办法 http://blog.csdn.net/zl_c/article/
参考资料 1 Frameset导致Cookies和Session丢失的原因及解决办法 http://blog.csdn.net/zl_c/article/
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号