一、Session简介:
Session 和 Cookie 一样,同样是在客户端和服务器之间进行会话时用来传输数据的一种方式,不过Cookie数据是保存在客户端的,而Session数据是存储在服务器端的,然后服务器会给客户端返回一个对应Session的ID存储在客户端的cookie中,当浏览器需要对应的数据时,就可以通过存储在客户端的Sessionid去服务器获取对应的数据。这样,也就可以解决用Cookie存储数据的安全性问题。
二、在Session的基本使用方法:
2.1 Session的使用过程:
从服务器获取一个session,如果能获取到session,就将Session的id记录下来,保存在浏览器;
如果获取不到Session,就说明Session还不存在,就创建一个Session,将数据保存在服务器端,将Sessionid保存在客户端的Cookie中。
获取Session:
- requset.getSession(); // 直接从服务器获取Session
- requset.getSession(boolean create) ; // 如果参数为true, 就直接创建一个session,如果为false,就相当于上面的方法从服务器获取一个session
2.2 Session的作用:
作为域对象使用:
- Session的作用范围:仅在当前Session域中有效(当前用户)
2.3 Session的生命周期:
- 创建session:requset.getSession(true);
- 给Session域中添加数据:Session对象 . setAttribute(Stirng s , Object o); // s相当一是一个标识符,o是存入的数据,获取数据的时候通过这个 字符串s获取o
- Session的销毁:
- 服务器非正常关闭的时候,Session被销毁
- 手动设置Session的最大生存时间:Session对象 . setMaxInactiveInterval(int interval) // 参数是以秒为单位,一般为正整数
- 手动删除Session : invalidate();
2.4 Session的特点:
- 可以存储任意类型的数据
- 存储的数据没有大小限制
- 适合用来存储私有数据
三、Session的使用案例:
3.1 Session基本使用案例:
后台往session中写入数据
前台jsp页面输出获取到的数据:
运行结果:
3.2 Session案例 — 模拟实现将商品加入购物车
简单写几个商品界面:
product_list.jsp 商品清单的界面,点击商品之后会跳转到对应的商品界面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>列表清单</title>
</head>
<body>
<table border="0px" >
<tr>
<td colspan="4">
<img src="../img/顶部.jpg" width="100%" />
</td>
</tr>
<tr>
<td>
<a href="001.jsp">
<img src="../img/001.jpg" />
</a>
</td>
<td>
<a href="002.jsp">
<img src="../img/002.jpg" />
</a>
</td>
<td>
<a href="003.jsp">
<img src="../img/003.jpg" />
</a>
</td>
<td>
<a href="004.jsp">
<img src="../img/004.jpg" />
</a>
</td>
</tr>
</table>
<hr/>
<a href="showCart.jsp">查看购物车</a>
</body>
</html>
001.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>watch</title>
</head>
<body>
<center>
<img src="../img/001.jpg" width="200" height="200"/>
</center>
<center>
价格:888
<a href="">立即购买</a>
<a href='/add2Cart?name="手表"'>加入购物车</a>
<a href="showCart.jsp">查看购物车</a>
<a href="product_list.jsp">回到主页</a>
</center>
</body>
</html>
002.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>watch</title>
</head>
<body>
<center>
<img src="../img/002.jpg" width="200" height="200"/>
</center>
<center>
价格:666
<a href="">立即购买</a>
<a href='/add2Cart?name="洗面奶"'>加入购物车</a>
<a href="showCart.jsp">查看购物车</a>
<a href="product_list.jsp">回到主页</a>
</center>
</body>
</html>
几个商品界面基本一样,这里就放两个商品的代码了。
查看购物车的页面:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%--
Created by IntelliJ IDEA.
User: ASUS
Date: 2019/6/1
Time: 16:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>show</title>
</head>
<body>
<table border="1px" cellpadding="0px" cellspacing="0px" align="center" >
<tr bgcolor="#ffe4c4">
<th width="100px">商品名称</th>
<th width="100px">商品数量</th>
</tr>
<c:choose>
<c:when test="${empty sessionScope.cart}">
<tr>
<td colspan="2">
购物车空空如也~~~
</td>
</tr>
</c:when>
<c:otherwise>
<c:forEach items="${cart}" var="item">
<tr bgcolor="gray">
<td >
<c:out value="${item.key}"/>
</td>
<td>
<c:out value=" ${[item.value]}"/>
</td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
</table>
</body>
</html>
后台获取信息并处理数据的Servlet
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Add2Cart extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 当用户点击加入购物车的时候 在后台获取点击的商品对应的id
String name = request.getParameter("name");
// 获取名字为cart的session数据
HttpSession session = request.getSession();
Map<String, Long> cartMap = (Map<String, Long>) session.getAttribute("cart");
// 如果为空,表示还没有创建购物车的Session
if (cartMap == null)
{
Map<String, Long> cart = new HashMap();
cart.put(name, 1L);
session.setAttribute("cart", cart);
}
// 如果不为空,说明已经创建过session了,现在需要在获取到的购物车中判断是否包含现在访问的
// 名称的商品,如果有当前商品,让商品的个数加一,如果没有当前商品,就放入当前商品,数量为1
else
{
if (cartMap.keySet().contains(name))
{
cartMap.put(name, cartMap.get(name)+1);
}
else
{
cartMap.put(name, 1L);
}
// 吧数据更新后的购物车存入session中
session.setAttribute("cart", cartMap);
}
// 设置最大生存时间,单位为秒
session.setMaxInactiveInterval(1200);
response.getWriter().write(name+"添加到购物车成功<hr/>");
// if (cartMap != null)
// System.out.println(cartMap.get(name));
response.getWriter().write("<a href='history/product_list.jsp'>回到首页</a>");
}
}
运行结果:
查看购物车的信息: