转载自: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: valuesimplement 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"};
}
}
相关推荐
关于asp.net的需要讲解,对session and cookies的讲解很精简。
使用Django来介绍CSRF and Cookies , Session
Bulletproof SSL and TLS by Ivan Ristić Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...
Resolved issue 1310: ChromeDriver hangs (and times out) when inspecting inactive background pages [['OS-All', 'Pri-2']] Resolved issue 824: ChromeDriver creates two cookies when the cookie to add ...
Maintain state with cookies, cookieless session state, and profiles Localize, configure, package, and deploy ASP.NET applications Use the ASP.NET MVC Framework to improve agility, testability, speed ...
Bug fix: When deploying the application as ISAPI, session tracking without cookies would fail Bug fix: When a IW application was compiled with runtime packages, TIWAppInfo.GetAppFullFileName was ...
最近因为工作的需要,要实现一个功能,就是需要通过发送短信进行注册,现在想把短信验证码放到服务器的session值中,当客户端收到短信并提交短信码时由asp.net服务端进行判断,那么如何共享这个session那么需要在...
:hammer_and_wrench: Next.js和Express(连接中间件)无状态会话实用程序,使用签名和加密的cookie来存储数据 这个 , 和后端实用程序允许您创建一个会话,然后通过签名和加密的印章将其存储在浏览器cookie中。 这...
The actual session id is not exposed which increases application security (this option requires that cookies are also enabled) CheckWindowId in ServerController.SecurityOptions. When set, IntraWeb ...
You may be able to send headers and cookies after you've already sent output ; through print or echo. You also may see performance benefits if your server is ; emitting less packets due to buffered ...
managing sessions and cookies; dealing with APIs; RSS; and XML; integrating with JavaScript and Ajax; accessing geo-location; spell checking and language translation; and a great deal more. Written ...
Chapter 2 - Installing Apache Chapter 3 - Installing PHP Part II - The Absolute Basics of Coding in PHP Chapter 4 - Mixing PHP and HTML Chapter 5 - Introducing Variables and Operators ...
Resolved issue 1142: cookies' httponly attribute is not returned [['Pri-2']] ----------ChromeDriver v2.18 (2015-08-19)---------- Supports Chrome v43-46 Resolved issue 1158: Unable to find elements ...
Resolved issue 1310: ChromeDriver hangs (and times out) when inspecting inactive background pages [['OS-All', 'Pri-2']] Resolved issue 824: ChromeDriver creates two cookies when the cookie to add ...
Subdomains, and Microsites 204 Optimization of Domain Names/URLs 211 Keyword Targeting 214 Content Optimization 225 Duplicate Content Issues 234 Controlling Content with Cookies and Session IDs 241 ...
by: MehdiAchour FriedhelmBetz AntonyDovgal ...•Session Extensions •Text Processing •Variable and Type Related Extensions •Web Services •Windows Only Extensions •XML Manipulation
The selected text compare allows you to select portions of text between 2 files and execute a compare on ONLY the se Using the SSH/telnet console A tutorial for UltraEdit/UEStudio's SSH/telent ...
介绍Rails session方法使我们可以访问Rails会话。 会话是使用Cookie实现的数据存储。 您可以在会话中存储简单的数据结构。 ActiveRecord模型,否。 字符串或数字数组,是的。 基本上,坚持使用数据文字-数字,字符串...
$ wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate '...
介绍Rails session方法使我们可以访问Rails会话。 会话是使用Cookie实现的数据存储。 您可以在会话中存储简单的数据结构。 ActiveRecord模型,否。 字符串或数字数组,是的。 基本上,坚持使用数据文字-数字,字符串...