會話技術之Session
session:服務器端會話技術
當我們第一次訪問的服務器的時候,服務器獲取id,
能獲取id
要拿着這個id去服務器中查找有無此session
若查找到了:直接拿過來將數據保存,需要將當前sessin的id返回給瀏覽器
若查找不到:創建一個session,將數據保存到這個session中,將當前session的id返回給瀏覽器
不能獲取id
創建一個session,將數據保存到這個session中,將當前session的id返回給瀏覽器
獲取一個session:
HttpSession request.getSession()
session域對象: xxxAttribute 生命周期: 創建:第一次調用request.getsession()創建 銷毀: 服務器非正常關閉 session超時 默認時間超時:30分鍾 web.xml有配置 手動設置超時:setMaxInactiveInterval(int 秒) 了解 手動干掉session ★session.invalidate() session用來存放私有的數據.
案例-添加、查看購物車:
步驟分析: 1.點擊添加到購物車的時候,提交到一個servlet add2CartServlet 需要將商品名稱攜帶過去 2.add2CartServlet中的操作 獲取商品的名稱 將商品添加到購物車 購物車的結構 Map<String 名稱,Integer 購買數量> 將購物車放入session中就可以了 將商品添加到購物車分析: 獲取購物車 判斷購物車是否為空 若為空: 第一次添加 創建一個購物車 將當前商品put進去.數量:1 將購物車放入session中 若不為空:繼續判斷購物車中是否有該商品 若有: 取出count 將數量+1 將商品再次放入購物車中 若沒有: 將當前商品put進去 數量:1 提示信息:你的xx已添加到購物車中 3.點擊購物車鏈接的時候 cart.jsp 從session獲取購物車 判斷購物車是否為空 若為空:提示信息 若不為空:遍歷購物車即可
項目的結構如下:
web.xml配置:
<servlet>
<servlet-name>Add2CartServlet</servlet-name>
<servlet-class>com.hjh.session.Add2CartServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Add2CartServlet</servlet-name>
<url-pattern>/add2Cart</url-pattern>
</servlet-mapping>
商品展示頁面product_list.jsp
<%@page import="com.hjh.utils.CookieUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>會員登錄</title>
<style> body { margin-top: 20px; margin: 0 auto; width: 100%; } .carousel-inner .item img { width: 100%; height: 300px; } .row{ height:280px; } .col-md-2{ float:left; margin-right: 100px; margin-left:10px; margin-top:10px; } </style>
</head>
<body>
<div class="row" style="width:1210px;margin:0 auto;">
<div class="col-md-2">
<a href="/CookieSession/getProductById?id=1">
<img src="./img/cs10001.jpg" width="170" height="170" style="display: inline-block;">
</a>
<p><a href="/CookieSession/getProductById?id=1" style='color:green'>衣服</a></p>
<p><font color="#FF0000">商城價:¥299.00</font></p>
</div>
<div class="col-md-2">
<a href="/CookieSession/getProductById?id=2">
<img src="img/cs10002.jpg" width="170" height="170" style="display: inline-block;">
</a>
<p><a href="/CookieSession/getProductById?id=2" style='color:green'>眼鏡</a></p>
<p><font color="#FF0000">商城價:¥299.00</font></p>
</div>
<div class="col-md-2">
<a href="/CookieSession/getProductById?id=3">
<img src="img/cs10003.jpg" width="170" height="170" style="display: inline-block;">
</a>
<p><a href="/CookieSession/getProductById?id=3" style='color:green'>包</a></p>
<p><font color="#FF0000">商城價:¥299.00</font></p>
</div>
<div class="col-md-2">
<a href="/CookieSession/getProductById?id=4">
<img src="img/cs10004.jpg" width="170" height="170" style="display: inline-block;">
</a>
<p><a href="/CookieSession/getProductById?id=4" style='color:green'>手機</a></p>
<p><font color="#FF0000">商城價:¥299.00</font></p>
</div>
</div>
<!-- 商品瀏覽記錄: -->
<div style="width:1210px;margin:0 auto; padding: 0 9px;border: 1px solid #ddd;border-top: 2px solid #999;height: 246px;">
<h4 style="width: 50%;float: left;font: 14px/30px " 微軟雅黑 ";">
瀏覽記錄<small><a href="/CookieSession/clearHistory">清空</a></small></h4>
<div style="width: 50%;float: right;text-align: right;"><a href="">more</a></div>
<div style="clear: both;"></div>
<div style="overflow: hidden;">
<ul style="list-style: none;">
<%
//獲取指定名稱的cookie
Cookie cookie=CookieUtils.getCookieByName("ids", request.getCookies()); //判斷id是否為空
if(cookie==null){ %>
<h2>暫無瀏覽記錄</h2>
<% }else{//ids=3-2-5
String [] arr=cookie.getValue().split("-"); for(String id:arr){ %>
<li style="width: 150px;height: 216;float: left;margin: 0 8px 0 0;padding: 0 18px 15px;
text-align: center;"><img src="img/cs1000<%=id %>.jpg" width="130px" height="130px" />
</li>
<% } } %>
</ul>
</div>
</div>
</body>
</html>
購物車頁面cart.jsp:
<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ 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>Insert title here</title>
</head>
<body>
<table border="1" align="center" width="30%">
<tr>
<td>商品名</td>
<td>數量</td>
</tr>
<%
//獲取購物車
Map<String,Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cart"); //判斷購物車是否為空
if(map==null){ //購物車為空
out.print("<tr><td colspan='2'>親,購物車空空如也,先去逛逛~</td></tr>"); }else{ //若不為空,顯示商品名及數量信息
for(String name:map.keySet()){ out.print("<tr><td>"+name+"</td><td>"+map.get(name)+"</td></tr>"); } } %>
</table>
<hr>
<center>
<a href="/CookieSession/product_list.jsp">繼續購物</a>
</center>
</body>
</html>
product_info1.htm:
<!doctype html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>會員登錄</title> <style> body { margin-top: 20px; margin: 0 auto; } .carousel-inner .item img { width: 100%; height: 300px; } </style> </head> <body> <div class="col-md-6"> <div><strong>衣服</strong></div> <div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;"> <div>編號:751</div> </div> <div style="margin:10px 0 10px 0;">億家價: <strong style="color:#ef0101;">¥:100元/件</strong> 參 考 價:
<del>¥99.00元/件</del> </div> <div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0;;background-color: #fffee6;"> <div style="margin:5px 0 10px 0;">白色</div> <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">購買數量: <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div> <div style="margin:20px 0 10px 0;;text-align: center;"> <a href="/CookieSession/add2Cart?name=衣服"> <input style="background: url('./images/product.gif') no-repeat scroll 0 -600px rgba(0, 0, 0, 0);
height:36px;width:127px;" value="加入購物車" type="button"> </a> 收藏商品</div> </div> </div> <div class="clear"></div> <div style="width:950px;margin:0 auto;"> <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;"> <strong>商品介紹</strong> </div> <div> <img src="img/cs10001.jpg"> </div> </div> </body> </html>
product_info2.htm
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>會員登錄</title>
<style> body { margin-top: 20px; margin: 0 auto; } .carousel-inner .item img { width: 100%; height: 300px; } </style>
</head>
<body>
<div class="container">
<div class="row">
<div style="margin:0 auto;width:950px;">
<div class="col-md-6">
<div><strong>眼鏡</strong></div>
<div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;">
<div>編號:751</div>
</div>
<div style="margin:10px 0 10px 0;">億家價: <strong style="color:#ef0101;">¥:200元/件</strong>
參 考 價: <del>¥199.00元/件</del>
</div>
<div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0
;background-color: #fffee6;">
<div style="margin:5px 0 10px 0;">白色</div>
<div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">購買數量: <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div>
<div style="margin:20px 0 10px 0;;text-align: center;">
<a href="/CookieSession/add2Cart?name=眼鏡">
<input style="background: url('./images/product.gif') no-repeat scroll 0 -600px
rgba(0, 0, 0, 0);height:36px;width:127px;" value="加入購物車" type="button">
</a> 收藏商品</div>
</div>
</div>
</div>
<div class="clear"></div>
<div style="width:950px;margin:0 auto;">
<div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;">
<strong>商品介紹</strong>
</div>
<div>
<img src="img/cs10002.jpg">
</div>
</div>
</div>
</div>
</body>
</html>
product_info3.htm
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>會員登錄</title>
<style> body { margin-top: 20px; margin: 0 auto; } .carousel-inner .item img { width: 100%; height: 300px; } </style>
</head>
<body>
<div class="container">
<div class="row">
<div style="margin:0 auto;width:950px;">
<div class="col-md-6">
<div><strong>包</strong></div>
<div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;">
<div>編號:751</div>
</div>
<div style="margin:10px 0 10px 0;">億家價: <strong style="color:#ef0101;">¥:300元/份</strong>
參 考 價: <del>¥299.00元/份</del>
</div>
<div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0
;background-color: #fffee6;">
<div style="margin:5px 0 10px 0;">白色</div>
<div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">購買數量: <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div>
<div style="margin:20px 0 10px 0;;text-align: center;">
<a href="/CookieSession/add2Cart?name=包">
<input style="background: url('./images/product.gif') no-repeat scroll 0 -600px
rgba(0, 0, 0, 0);height:36px;width:127px;" value="加入購物車" type="button">
</a> 收藏商品</div>
</div>
</div>
</div>
<div class="clear"></div>
<div style="width:950px;margin:0 auto;">
<div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;">
<strong>商品介紹</strong>
</div>
<div>
<img src="img/cs10003.jpg">
</div>
</div>
</div>
</div>
</body>
</html>
product_info4.htm
<!doctype html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>會員登錄</title> <style> body { margin-top: 20px; margin: 0 auto; } .carousel-inner .item img { width: 100%; height: 300px; } </style> </head> <body> <div class="container"> <div class="row"> <div style="margin:0 auto;width:950px;"> <div class="col-md-6"> <div><strong>手機</strong></div> <div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;"> <div>編號:751</div> </div> <div style="margin:10px 0 10px 0;">億家價: <strong style="color:#ef0101;">¥:400元/份</strong> 參 考 價: <del>¥388.00元/份</del> </div> <div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0;;background-color: #fffee6;"> <div style="margin:5px 0 10px 0;">白色</div> <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">購買數量: <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div> <div style="margin:20px 0 10px 0;;text-align: center;"> <a href="/CookieSession/add2Cart?name=手機"> <input style="background: url('./images/product.gif') no-repeat scroll 0 -600px rgba(0, 0, 0, 0);height:36px;width:127px;" value="加入購物車" type="button"> </a> 收藏商品</div> </div> </div> </div> <div class="clear"></div> <div style="width:950px;margin:0 auto;"> <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;"> <strong>商品介紹</strong> </div> <div> <img src="img/cs10004.jpg" style="width:300px"> </div> </div> </div> </div> </body> </html>
Add2CartServlet.java源碼:
package com.hjh.session; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 添加到購物車、查看購物車 */
public class Add2CartServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置編碼
response.setContentType("text/html;charset=UTF-8"); //1.獲取商品的名稱,要考慮中文亂碼
String name = request.getParameter("name"); //2.將商品添加到購物車 //2.1從session中獲取購物車 商品名 數量
Map<String,Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cart"); Integer count= null; //2.2判斷購物車是否為空
if(map==null) { //第一次購物,創建購物車
map = new HashMap<>(); //創建完購物車,放入session中
request.getSession().setAttribute("cart", map); //第一次加入商品到購物車,默認不選擇數量為1
count=1; }else { //購物車不為空,繼續判斷購物車中是否有同種商品 //map購物車通過商品名查找其數量
count = map.get(name); if(count==null) { //購物車沒有當前商品
count = 1; }else { //購物車已經存在該商品
count++; } } //將商品以及數量等新數據放入購物車
map.put(name,count); //3.提示信息
PrintWriter w = response.getWriter(); w.print("已經將<b>"+name+"</b>添加到購物車中<hr>"); w.print("<a href='"+request.getContextPath()+"/product_list.jsp'>繼續購物</a> "); w.print("<a href='"+request.getContextPath()+"/cart.jsp'>查看購物車</a> "); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
啟動項目,瀏覽器地址欄中輸入以下url,回車,product_list.jsp商品頁面展示如下:
點擊第一張衣服的圖片,跳轉到product_info1.jsp頁面,顯示衣服的詳細信息,如下圖:
點擊加入購物車,頁面跳轉顯示如下;
點擊繼續購物,跳轉到product_list.jsp頁面;點擊查看購物車,跳轉到cart.jsp頁面
案例2-擴展清空購物車:
思路1:將購物車移除 思路2:將session干掉 步驟分析: 在cart.jsp上添加一個超鏈接 清空購物車 <a href="/day1101/clearCart">清空購物車</a> 在clearCart中需要調用session.invalidate() 重定向到購物車頁面
在案例一加入購物車的項目的基礎上,需要增加以下3個文件:
web.xml配置:
<servlet>
<servlet-name>ClearCartServlet</servlet-name>
<servlet-class>com.hjh.session.ClearCartServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ClearCartServlet</servlet-name>
<url-pattern>/clearCart</url-pattern>
</servlet-mapping>
cart.jsp購物車頁面:
<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ 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>Insert title here</title>
</head>
<body>
<table border="1" align="center" width="30%">
<tr>
<td>商品名</td>
<td>數量</td>
</tr>
<%
//獲取購物車
Map<String,Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cart"); //判斷購物車是否為空
if(map==null){ //購物車為空
out.print("<tr><td colspan='2'>親,購物車空空如也,先去逛逛~</td></tr>"); }else{ //若不為空,顯示商品名及數量信息
for(String name:map.keySet()){ out.print("<tr><td>"+name+"</td><td>"+map.get(name)+"</td></tr>"); } } %>
</table>
<hr>
<center>
<a href="/CookieSession/product_list.jsp">繼續購物</a> <a href="/CookieSession/clearCart">清空購物車</a>
</center>
</body>
</html>
ClearCartServlet.java源碼:
package com.hjh.session; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * 清空購物車 */
public class ClearCartServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置編碼
response.setContentType("text/html;charset=UTF-8"); //獲取session
HttpSession session = request.getSession(); //調用session.invalidate() 清空購物車
session.invalidate(); //重定向
response.sendRedirect(request.getContextPath()+"/cart.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
特別注意:①編碼要統一
②servlet類要配置正確
③路徑要寫對