会话技术之Session(购物车加入、查看和清空)


会话技术之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">商城价:&yen;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">商城价:&yen;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">商城价:&yen;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">商城价:&yen;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> &nbsp;收藏商品</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> &nbsp;收藏商品</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> &nbsp;收藏商品</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> &nbsp;收藏商品</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>&nbsp;&nbsp;&nbsp;&nbsp;"); w.print("<a href='"+request.getContextPath()+"/cart.jsp'>查看购物车</a>&nbsp;&nbsp;&nbsp;&nbsp;"); } 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>&nbsp;&nbsp;&nbsp;&nbsp; <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类要配置正确

     ③路径要写对

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM