深入理解 HTTP 会话管理
1. 使用 HttpSession
使用 HttpSession
通常是一个三步过程:
1. 检索与请求关联的会话。
2. 从会话中添加或删除属性的名值对。
3. 如果需要,关闭或使会话无效。
以下是一个示例代码,展示了 ShoppingCartServlet
的 doPost()
方法中如何使用 HttpSession
:
//code for the doPost() method of ShoppingCartServlet
public void doPost(HttpServletRequest req,
HttpServletResponse res)
{
HttpSession session = req.getSession(true);
List listOfItems =
(List) session.getAttribute("listofitems");
if(listOfItems == null)
{
listOfItems = new Vector();
session.setAttribute("listofitems", listOfItems);
}
String itemcode = req.getParameter("itemcode");
String comman