转载自: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和Cookies是两种常见的用户状态管理机制,它们用来跟踪用户在网站上的行为和信息。本文将深入探讨这两个概念以及相关的知识点。 首先,让我们了解什么是Session。Session是一种服务器端的状态...
本文将详细介绍一款基于Ajax和ASP的小程序,它专门用于调试ASP语句,特别是涉及到session、cookies和application对象的调试。 **一、调试ASP语句的重要性** 调试是编程过程中的关键环节,对于ASP开发者来说,能够...
Session是一个服务器端的状态管理工具,它为每个用户创建一个唯一的标识(SessionID),这个标识被存储在用户的浏览器cookies中。每当用户请求一个新的页面时,服务器会根据SessionID找到与之关联的数据。 二、...
2. **生命周期**:Session也有生命周期,服务器可以设置过期时间,过期后Session将被清除。 3. **安全性**:Session比Cookie更安全,因为数据存储在服务器端,不会暴露给客户端。 4. **负载均衡**:在多服务器环境下...
在`Context_BeginRequest`事件处理程序中,我们可以访问`HttpContext.Current.Session`和`HttpContext.Current.Request.Cookies`来获取和检查Session和Cookie。如果Session为空或Cookie过期,我们可以采取相应的措施...
在IT行业中,网络应用程序的用户认证是至关重要的。本文将深入探讨如何在C#环境中,特别是在Visual Studio 2005环境下,利用Cookie和...压缩包中的CookieAndSession项目正是这样一个实践示例,供学习者参考和实践。
2. **Session机制**: - **Session概述**:当浏览器访问服务器时,服务器检查是否存在与该浏览器相关的Session。如果不存在,就创建一个新的Session,并将数据存储进去。下次浏览器再次发送请求时,服务器会识别出...
Bulletproof SSL and TLS by Ivan Ristić Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...
#### Session与Cookies的基础概念及其替代方案 **Session与Cookies的概念:** 在Web开发中,Session 和 Cookies 是两种常用的状态管理技术,用于维护用户的会话状态。 - **Session**:一种服务器端的技术,用于...
与Cookies不同的是,Session数据通常存储在服务器端,而Cookies数据则存储在客户端浏览器上。 #### Django Session机制 Django提供了内置的Session支持,使得在应用程序中实现用户状态跟踪变得简单。Django的...
当一个用户访问网站时,PHP生成唯一的session id,并通过cookies或URL传递,确保用户可以被识别。在PHP中,使用session_start()函数开始会话,并通过$_SESSION超全局数组存储数据。 接下来,购物车是电子商务网站的...
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 ...
- **Client-Side Storage:** Cookies or local storage can be used to store session tokens on the client side. This approach is simple but raises security concerns since data stored on the client can be...
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 ...
- This method initializes session variables and redirects to an error page if the user's session cannot be established. - It sets the logo image source and checks if the trial period has expired. 2...
最近因为工作的需要,要实现一个功能,就是需要通过发送短信进行注册,现在想把短信验证码放到服务器的session值中,当客户端收到短信并提交短信码时由asp.net服务端进行判断,那么如何共享这个session那么需要在...
:hammer_and_wrench: Next.js和Express(连接中间件)无状态会话实用程序,使用签名和加密的cookie来存储数据 这个 , 和后端实用程序允许您创建一个会话,然后通过签名和加密的印章将其存储在浏览器cookie中。 这...