session对象表明一次用户会话,一次用户会话的含义是:从客户端浏览器链接服务器开始,到客户端浏览器与服务器断开为止,这个过程就是一个会话。session范围内的属性能够在多个页面的跳转之间共享,一旦浏览器关闭,session就结束,session范围内的属性将所有丢失。
使用setAttribute(String attName, Object attValue)方法设置attName属性的值为attValue
使用getAttribute(String attName)方法返回session范围内的attName属性的值
一般只应该把与用户会话状态相关的信息放入session范围内,不要仅仅为了两个页面之间交换信息,就将信息放入session范围内,若是仅仅为了两个页面交换信息,能够将该信息放入request范围内,而后forward请求便可。
session机制一般用于保存客户端状态信息,这些状态信息须要保存到Web服务器的硬盘上,因此要求session里的属性必须是可序列化的,不然将引起异常。
以下页面session_order.jsp用于填写购买的商品数量,提交后转发到session_show.jsp页面,在该页面显示用户购买的各商品的数量, session_order.jsp页面内容以下:html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>利用session对象保存在不一样页面间传递数据</title> </head> <body> <form method="post" action="session_show.jsp" target="_blank"> 书籍: <input type="text" name="book" /><br /> 电脑: <input type="text" name="computer" /><br /> 手机: <input type="text" name="phone" /><br /> <input type="submit" value="购买" /> </form> </body> </html>
session_show.jsp页面内容以下:java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import = "java.util.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>从session对象中读取数据</title> </head> <body> <% Map<String, Integer> cart = (Map<String, Integer>)session.getAttribute("cart"); if(cart == null) { cart = new HashMap<String, Integer>(); cart.put("书籍", 0); cart.put("电脑", 0); cart.put("手机", 0); } Enumeration<String> products = request.getParameterNames(); while(products.hasMoreElements()) { String productName = products.nextElement(); if(productName.equalsIgnoreCase("book")) { int addNo = Integer.valueOf(request.getParameter(productName).trim()).intValue(); int oldNo = cart.get("书籍").intValue(); cart.put("书籍", oldNo + addNo); } else if(productName.equalsIgnoreCase("computer")) { int addNo = Integer.valueOf(request.getParameter(productName).trim()).intValue(); int oldNo = cart.get("电脑").intValue(); cart.put("电脑", oldNo + addNo); } else if(productName.equalsIgnoreCase("phone")) { int addNo = Integer.valueOf(request.getParameter(productName).trim()).intValue(); int oldNo = cart.get("手机").intValue(); cart.put("手机", oldNo + addNo); } } session.setAttribute("cart", cart); %> 您所购买的物品清单:<br /> <% Iterator it = cart.keySet().iterator(); while(it.hasNext()) { String key = (String)it.next(); %> <%=key + ":" + cart.get(key) + "<br />"%> <% } %> </body> </html>
点击session_order.jsp页面的"提交"按钮后,跳转到session_show.jsp页面,在该页面中能够看到用户购买的各商品数量,再次点击"提交"按钮或刷新session_show.jsp页面,会看到用户购买的各商品数量加倍。直到浏览器关闭。浏览器