第六节——前台用户系统的实现

执键写春秋
• 阅读 1425

6. 前台用户系统的实现

6.1 主页

http://localhost:8080/

6.1.1 视图层页面

【src/main/resources/templates/user/index.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>主页</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script src="js/jquery.min.js"></script>
<script type="text/javascript" th:inline="javascript">
    function focus(gid){
        $.ajax(
                {
                    //请求路径,要注意的是url和th:inline="javascript"
                    url : [[@{/focus/focus}]],
                    //请求类型
                    type : "post",
                    contentType : "application/json",
                    //data表示发送的数据
                    data : JSON.stringify({
                        id : gid
                    }),
                    //成功响应的结果
                    success : function(obj){//obj响应数据
                        if(obj == "no"){
                            alert("您已收藏该商品!");
                        }else if(obj == "ok"){
                            alert("成功收藏该商品");
                        }else{
                            alert("你还没有登录!!!")
                        }
                    },
                    error : function() {
                        alert("处理异常!");
                    }
                }    
            );
    }

</script>
</head>
<body>
    <!-- 加载header.html -->
    <div th:include="user/header"></div>
    <div class="container">
        <div>
            <h4>推荐商品</h4>
        </div>
        <div class="row">
            <div class="col-xs-6 col-md-2" th:each="rGoods:${recommendGoods}">
                <a th:href="'goodsDetail?id=' + ${rGoods.id}" class="thumbnail"> <img
                    alt="100%x180" th:src="'images/' + ${rGoods.gpicture}"
                    style="height:200px; width: 100%; display: block;">
                </a>
                <div class="caption" style="text-align: center;">
                    <div>
                        <span th:text="${rGoods.gname}"></span>
                    </div>
                    <div>
                        <span style="color: red;">&yen;
                            <span th:text="${rGoods.grprice}"></span>
                        </span>
                        <span class="text-dark" style="text-decoration: line-through;"> &yen;
                            <span th:text="${rGoods.goprice}"></span>
                        </span>
                    </div>
                    <a th:href="'javascript:focus('+ ${rGoods.id} +')'" class="btn btn-primary"
                        style="font-size: 10px;">加入收藏</a>
                </div>
            </div>
        </div>
        <!-- *********************************************************** -->
        <div>
            <h4>最新商品</h4>
        </div>
        <div class="row">
            <div class="col-xs-6 col-md-2" th:each="lGoods:${lastedGoods}">
                <a th:href="'goodsDetail?id=' + ${lGoods.id}"  class="thumbnail"> <img alt="100%x180"
                    th:src="'images/' + ${lGoods.gpicture}"
                    style="height: 180px; width: 100%; display: block;">
                </a>
                <div class="caption" style="text-align: center;">
                    <div>
                        <span th:text="${lGoods.gname}"></span>
                    </div>
                    <div>
                        <span style="color: red;">&yen;
                            <span th:text="${lGoods.grprice}"></span>
                        </span> 
                        <span class="text-dark" style="text-decoration: line-through;">&yen;
                            <span th:text="${lGoods.goprice}"></span>
                        </span>
                    </div>
                    <a th:href="'javascript:focus('+ ${lGoods.id} +')'"  class="btn btn-primary" style="font-size: 10px;">加入收藏</a>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

【src/main/resources/templates/user/header.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>导航页</title>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<style type="text/css">
     .carousel{
         height: 280px;
         background-color: #000;
      }
      .carousel .item{
         height: 280px;
         background-color: #000;
      }
      .carousel img{
         width: 100%;
      }
</style>
</head>
<body>
    <div class="container-fruid">
        <div class="navbar navbar-default navbar-fixed-top" role="navigation"
            style="padding-left: 30px;">
            <div class="navbar-header">
                <span class="navbar-brand">欢迎光临eBusiness</span>
            </div>
            <ul class="nav navbar-nav">
                <li><a th:href="@{user/toRegister}">注册</a></li>
                <li>
                    <a th:href="(${session.currentUser} == null)?'user/toLogin':'#'" >
                        <span th:if="${session.currentUser} == null" >
                            登录
                        </span>
                        <span th:if="${session.currentUser} != null" >
                            欢迎<span th:text="${session.currentUser.email}" ></span>
                        </span>
                    </a>
                </li>
                <li><a th:href="@{admin/toLogin}">后台</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right" style="padding-right: 30px;">
                <li><a href="user/userInfo">修改密码</a></li>
                <li><a href="cart/selectCart">我的购物车</a></li>
                <li><a href="/focus/myFocus">我的收藏</a></li>
                <li><a href="border/myOder">我的订单</a></li>
                <li class="dropdown"><a href="##" data-toggle="dropdown"
                    class="dropdown-toggle">关于我们<span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="##">联系我们</a></li>
                        <li><a href="##">投诉建议</a></li>
                    </ul>
                </li>
            </ul>
        </div>
        <!-- ************************************************** -->
        <div id="carousel-example-generic" class="carousel slide"
            data-ride="carousel" style="margin-top: 20px;">
            <!-- Indicators 小圆圈-->
            <ol class="carousel-indicators">
                <li data-target="#carousel-example-generic" 
                th:each="advertise,adstat:${advertisementGoods}" 
                th:data-slide-to="${adstat.index}"
                th:class="(${adstat.index}==0)? 'active' : ''"></li>
            </ol>
            <!-- 滚动广告图片 -->
            <div class="carousel-inner" role="listbox">
                <div th:each="advertise,adstat:${advertisementGoods}" th:class="(${adstat.index}==0)? 'item active' : 'item'">
                    <img th:src="'images/' + ${advertise.gpicture}" th:alt="${adstat.index + 1}">
                    <div class="carousel-caption"><span th:text="${advertise.gname}"></span></div>
                </div>
            </div>
            <!-- Controls -->
            <a class="left carousel-control" href="#carousel-example-generic"
                role="button" data-slide="prev"> <span
                class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
                <span class="sr-only">Previous</span>
            </a> <a class="right carousel-control" href="#carousel-example-generic"
                role="button" data-slide="next"> <span
                class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
                <span class="sr-only">Next</span>
            </a>
        </div>
        <!-- *************************************** -->
        <div class="navbar navbar-default " role="navigation">
            <ul class="nav navbar-nav" style="padding-left: 50px;">
                <li><a th:href="@{/}">首页</a></li>
                <li th:each="gty:${goodsType}">
                    <a th:href="'?tid=' + ${gty.id}"><span th:text="${gty.typename}"></span></a>
                </li>
            </ul>
            <form action="search" class="navbar-form navbar-right" style="padding-right: 50px;">
                <div class="form-group">
                    <input type="text" class="form-control" name="myKey" placeholder="请输入关键词" />
                </div>
                <button type="submit" class="btn btn-default">搜索</button>
            </form>
        </div>
    </div>
</body>
</html>

第六节——前台用户系统的实现

6.1.2 控制器层方法

package pers.xsc.online_shopping.controller.before;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import pers.xsc.online_shopping.service.before.IndexService;

@Controller
public class IndexController {
    @Autowired
    IndexService indexService ;

    @RequestMapping("/")
    public String index(Model model, Integer tid) {
        return indexService.index(model, tid);
    }

}

6.1.3 业务层接口及实现

根据前台主页展示需求,分为四块:一是提供广告区商品信息,二是提供导航栏商品类型信息,三是提供推荐区商品信息,四是提供最新区商品信息。

package pers.xsc.online_shopping.service.before;

import org.springframework.ui.Model;

public interface IndexService {
    public String index(Model model, Integer tid);
}
package pers.xsc.online_shopping.service.before.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import pers.xsc.online_shopping.mapper.before.IndexMapper;
import pers.xsc.online_shopping.service.before.IndexService;
@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    IndexMapper indexMapper ;
    @Override
    public String index(Model model, Integer tid) {
        if(tid == null)
            tid = 0;
        //广告区商品
        model.addAttribute("advertisementGoods",  indexMapper.selectAdvertisementGoods());
        //导航栏商品类型
        model.addAttribute("goodsType",  indexMapper.selectGoodsType());
        //推荐商品
        model.addAttribute("recommendGoods",  indexMapper.selectRecommendGoods(tid));
        //最新商品
        model.addAttribute("lastedGoods",  indexMapper.selectLastedGoods(tid));
        return "user/index";
    }

}

6.1.4 持久层

package pers.xsc.online_shopping.mapper.before;

import pers.xsc.online_shopping.entity.Goods;
import pers.xsc.online_shopping.entity.GoodsType;

import java.util.List;

public interface IndexMapper {
//广告
    public List<Goods> selectAdvertisementGoods();
//导航栏商品类型
    public List<GoodsType> selectGoodsType();
//推荐
    public List<Goods> selectRecommendGoods(Integer tid);
//最新
    public List<Goods> selectLastedGoods(Integer tid);
}

6.1.5 映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="pers.xsc.online_shopping.mapper.before.IndexMapper">
    <!-- 查询广告商品 -->
    <select id="selectAdvertisementGoods"  resultType="pers.xsc.online_shopping.entity.Goods">
        select
            gt.*, gy.typename
        from
            goods_table gt,goodstype_table gy
        where
            gt.goodstype_id = gy.id
          and gt.isAdvertisement = 1
        order by  gt.id desc limit 5
    </select>

    <!-- 查询商品类型 -->
    <select id="selectGoodsType" resultType="pers.xsc.online_shopping.entity.GoodsType">
        select * from goodstype_table
    </select>
    <!-- 查询推荐商品 -->
    <select id="selectRecommendGoods" resultType="pers.xsc.online_shopping.entity.Goods" parameterType="integer">
        select
        gt.*, gy.typename
        from
        goods_table gt,goodstype_table gy
        where
        gt.goodstype_id = gy.id
        and gt.isRecommend = 1
        <if test="tid != 0">
            and gy.id = #{tid}
        </if>
        order by  gt.id desc limit 6
    </select>
    <!-- 查询最新商品 -->
    <select id="selectLastedGoods" resultType="pers.xsc.online_shopping.entity.Goods" parameterType="integer">
        select
        gt.*, gy.typename
        from
        goods_table gt,goodstype_table gy
        where
        gt.goodstype_id = gy.id
        <if test="tid != 0">
            and gy.id = #{tid}
        </if>
        order by  gt.id desc limit 6
    </select>

</mapper>

6.2 商品详情

6.2.1 视图层页面

【src/main/resources/templates/user/goodsDetail.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>商品页面</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script src="js/jquery.min.js"></script>
<script type="text/javascript" th:inline="javascript">
    function focus(){
            $.ajax(
                {
                    //请求路径,要注意的是url和th:inline="javascript"
                    url : [[@{/cart/focus}]],
                    //请求类型
                    type : "post",
                    contentType : "application/json",
                    //data表示发送的数据
                    data : JSON.stringify({
                        id : $("#gid").val()
                    }),
                    //成功响应的结果
                    success : function(obj){//obj响应数据
                        if(obj == "no"){
                            alert("您已收藏该商品!");
                        }else if(obj == "ok"){
                            alert("成功收藏该商品");
                        }else{
                            alert("您没有登录,请登录!");
                        }
                    },
                    error : function() {
                        alert("处理异常!");
                    }
                }    
            );
    }
    function putCart(){
        if(!(/(^[1-9]\d*$)/.test($("#buyNumber").val()))){
            alert("购买量请输入正整数!");
            $("#buyNumber").focus();
            return;
        }
        if(parseInt($("#buyNumber").val()) > parseInt($("#gstore").text())){
            alert("购买量超出库存!");
            $("#buyNumber").focus();
            return;
        }
        //获取路径
        var pathName=window.document.location.pathname;
        //截取,得到项目名称
        var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
        window.location.href = projectName + "/cart/putCart?id=" +  $("#gid").val() + "&buyNumber=" + $("#buyNumber").val();
    }
</script>
</head>
<body>
    <!-- 加载header.html -->
    <div th:include="user/header"></div>
    <div class="container">
        <div class="row">
            <div class="col-xs-6 col-md-3">
                <img
                    th:src="'images/' + ${goods.gpicture}"
                    style="height: 220px; width: 280px; display: block;">
            </div>
            <div class="col-xs-6 col-md-3">
                <p>商品名:<span th:text="${goods.gname}"></span></p>
                <p>
                    商品折扣价:<span style="color: red;">&yen;
                        <span th:text="${goods.grprice}"></span>
                    </span>
                </p>
                <p>
                    商品原价:
                    <span class="text-dark" style="text-decoration: line-through;"> &yen;
                        <span th:text="${goods.goprice}"></span>
                    </span>
                </p>
                <p>
                    商品类型:<span th:text="${goods.typename}"></span>
                </p>
                <p>
                    库存:<span id="gstore"  th:text="${goods.gstore}"></span>
                </p>
                <p>
                    <input type="text" size="12" class="form-control" placeholder="请输入购买量" id="buyNumber" name="buyNumber"/>
                    <input type="hidden" name="gid" id="gid" th:value="${goods.id}"/>
                </p>
                <p>
                    <a href="javascript:focus()" class="btn btn-primary"
                        style="font-size: 10px;">加入收藏</a>
                    <a href="javascript:putCart()" class="btn btn-success"
                        style="font-size: 10px;">加入购物车</a>
                </p>
            </div>
        </div>
    </div>
</body>
</html>

第六节——前台用户系统的实现

6.2.2 控制器层方法

@RequestMapping("/goodsDetail")
    public String goodsDetail(Model model, Integer id) {
        return indexService.goodsDetail(model, id);
    }

6.2.3 业务层接口及实现

根据详情页需求,需要根据其ID进行查询,提供所点击商品的所有信息,包括商品名、商品图片、商品折扣价、商品类型、商品库存。同时,广告区和导航栏区信息正常提供。

public String goodsDetail(Model model, Integer id);
@Override
    public String goodsDetail(Model model, Integer id) {
        //广告区商品
        model.addAttribute("advertisementGoods",  indexMapper.selectAdvertisementGoods());
        //导航栏商品类型
        model.addAttribute("goodsType",  indexMapper.selectGoodsType());
        //商品详情
        model.addAttribute("goods",  indexMapper.selectAGoods(id));
        return "user/goodsDetail";
    }

6.2.4 持久层

public Goods selectAGoods(Integer id);

6.2.5 映射文件

 <!-- 查询商品详情 -->
    <select id="selectAGoods"  resultType="pers.xsc.online_shopping.entity.Goods">
        select
            gt.*, gy.typename
        from
            goods_table gt,goodstype_table gy
        where
            gt.goodstype_id = gy.id
          and gt.id = #{id}
    </select>

6.3 商品搜索

6.3.1 视图层页面

【src/main/resources/templates/user/searchResults.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>主页</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script src="js/jquery.min.js"></script>
<script type="text/javascript" th:inline="javascript">
    function focus(gid){
        $.ajax(
                {
                    //请求路径,要注意的是url和th:inline="javascript"
                    url : [[@{/cart/focus}]],
                    //请求类型
                    type : "post",
                    contentType : "application/json",
                    //data表示发送的数据
                    data : JSON.stringify({
                        id : gid
                    }),
                    //成功响应的结果
                    success : function(obj){//obj响应数据
                        if(obj == "no"){
                            alert("您已收藏该商品!");
                        }else if(obj == "ok"){
                            alert("成功收藏该商品");
                        }else{
                            alert("您没有登录,请登录!");
                        }
                    },
                    error : function() {
                        alert("处理异常!");
                    }
                }    
            );
    }
</script>
</head>
<body>
    <!-- 加载header.html -->
    <div th:include="user/header"></div>
    <div class="container">
        <div>
            <h4>搜索结果</h4>
        </div>
        <div class="row">
            <div class="col-xs-6 col-md-2" th:each="rGoods:${searchgoods}">
                <a th:href="'goodsDetail?id=' + ${rGoods.id}" class="thumbnail"> <img
                    alt="100%x180" th:src="'images/' + ${rGoods.gpicture}"
                    style="height: 180px; width: 100%; display: block;">
                </a>
                <div class="caption" style="text-align: center;">
                    <div>
                        <span th:text="${rGoods.gname}"></span>
                    </div>
                    <div>
                        <span style="color: red;">&yen;
                            <span th:text="${rGoods.grprice}"></span>
                        </span>
                        <span class="text-dark" style="text-decoration: line-through;"> &yen;
                            <span th:text="${rGoods.goprice}"></span>
                        </span>
                    </div>
                    <a th:href="'javascript:focus('+ ${rGoods.id} +')'" class="btn btn-primary"
                        style="font-size: 10px;">加入收藏</a>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

第六节——前台用户系统的实现

6.3.2 控制器层方法

@RequestMapping("/search")
    public String search(Model model , String myKey){
        return indexService.search(model,myKey);
    }

6.3.3 业务层接口及实现

根据结果页面需求,需要根据前台传回的关键字进行模糊查询,返回一个存放一个或多个商品信息对象的搜索集合。同时,广告区和导航栏区信息正常提供。

public String search(Model model, String mykey);
@Override
    public String search(Model model, String mykey) {
        //广告区商品
        model.addAttribute("advertisementGoods",  indexMapper.selectAdvertisementGoods());
        //导航栏商品类型
        model.addAttribute("goodsType",  indexMapper.selectGoodsType());
        //商品搜索
        model.addAttribute("searchgoods",  indexMapper.search(mykey));
        return "user/searchResult";
    }

6.3.4 持久层

 public List<Goods> search(String mykey);

6.3.5 映射文件

<!-- 首页搜索 -->
    <select id="search" resultType="pers.xsc.online_shopping.entity.Goods" parameterType="String">
        select gt.*, gy.typename
        from goods_table gt,goodstype_table gy
        where gt.goodstype_id = gy.id and gt.gname like concat('%',#{mykey},'%')
    </select>

6.4 用户注册与登录

6.4.1 视图层页面

【src/main/resources/templates/user/register.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>注册页面</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script src="js/jquery.min.js"></script>
<script src="js/common.js"></script>
<script type="text/javascript" th:inline="javascript">
    function checkEmail(){
        if(checkNull($("#bemail").val(), "请输入邮箱!")){
            $.ajax(
                {//提交检查用户名是否可用请求
                    //请求路径,要注意的是url和th:inline="javascript"
                    url : [[@{/user/isUse}]],
                    //请求类型
                    type : "post",
                    contentType : "application/json",
                    //data表示发送的数据
                    data : JSON.stringify({
                        bemail : $("#bemail").val()
                    }),
                    //成功响应的结果
                    success : function(obj){//obj响应数据
                        if(obj == "no"){
                            $("#isExit").html("<font color=red size=5>×</font>");
                            alert("用户已存在,请修改!");
                        }else{
                            $("#isExit").html("<font color=green size=5>√</font>");
                            alert("用户可用");
                        }
                    },
                    error : function() {
                        alert("处理异常!");
                    }
                }    
            );
        }
    }
    function checkBpwd(){
        if($("#pwd").val() != $("#rebpwd").val()){
            alert("两次密码不一致!");
            return false;
        }
        document.myform.submit();
    }
</script>
<body>
    <div class="container">
          <div class="bg-primary"  style="width:70%; height: 60px;padding-top: 1px;">
           <h3 align="center">用户注册</h3>
       </div>
        <br><br>
        <form action="user/register" name="myform" method="post" th:object="${user}"  class="form-horizontal" role="form" >
            <div class="form-group has-success">
                <label class="col-sm-2 col-md-2 control-label">邮箱</label>
                <div class="col-sm-4 col-md-4">
                    <table style="width:100%">
                        <tr>
                            <td><input type="email" class="form-control"
                     placeholder="请输入您的邮箱"
                    th:field="*{email}" onblur="checkEmail()"/></td>
                             <td>
                                 <span id="isExit"></span>
                             </td>
                        </tr>
                    </table>
                    <span th:errors="*{email}"></span>
                </div>
            </div>

            <div class="form-group has-success">
                  <label class="col-sm-2 col-md-2 control-label">密码</label>
                  <div class="col-sm-4 col-md-4">
                          <input type="password" class="form-control"
                     placeholder="请输入您的密码" th:field="*{pwd}" />
                     <span th:errors="*{pwd}"></span>
                  </div>
             </div>

            <div class="form-group has-success">
                  <label class="col-sm-2 col-md-2 control-label">确认密码</label>
                  <div class="col-sm-4 col-md-4">
                          <input type="password" class="form-control"
                     placeholder="请输入您的密码" th:field="*{rebpwd}"/>
                  </div>
             </div>

            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="button" onclick="checkBpwd()" class="btn btn-success" >注册</button>
                    <button type="reset" class="btn btn-primary" >重置</button>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

第六节——前台用户系统的实现 【src/main/resources/templates/user/loginr.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>登录页面</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script type="text/javascript" th:inline="javascript">
    function refreshCode(){
        document.getElementById("mycode").src = [[@{/validateCode}]] + "?t=" + Math.random();
    }
</script>
<body>
    <div class="container">
        <div class="bg-primary"  style="width:70%; height: 60px;padding-top: 1px;">
           <h3 align="center">用户登录</h3>
       </div>
        <br><br>
        <form action="user/login" name="myform" method="post" th:object="${user}"  class="form-horizontal" role="form" >
            <div class="form-group has-success">
                <label class="col-sm-2 col-md-2 control-label">邮箱</label>
                <div class="col-sm-4 col-md-4">
                    <input type="email" class="form-control"
                     placeholder="请输入您的邮箱"
                    th:field="*{email}"/>
                    <span th:errors="*{email}"></span>
                </div>
            </div>

            <div class="form-group has-success">
                  <label class="col-sm-2 col-md-2 control-label">密码</label>
                  <div class="col-sm-4 col-md-4">
                          <input type="password" class="form-control"
                     placeholder="请输入您的密码" th:field="*{pwd}"/>
                     <span th:errors="*{pwd}"></span>
                  </div>
             </div>

             <div class="form-group has-success">
                  <label class="col-sm-2 col-md-2 control-label">验证码</label>
                  <div class="col-sm-4 col-md-4">
                          <table style="width: 100%">
                              <tr>
                                  <td><input type="text" class="form-control"
                     placeholder="请输入验证码" th:field="*{code}"/></td>
                                 <td>
                                     <img th:src="@{/validateCode}" id="mycode">
                                 </td>
                                 <td>
                                     <a href="javascript:refreshCode()">看不清换一张</a>
                                 </td>
                              </tr>
                          </table>
                  </div>
             </div>


            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit"class="btn btn-success" >登录</button>
                    <button type="reset" class="btn btn-primary" >重置</button>
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <font size="6" color="red">
                        <span th:text="${errorMessage }"></span>
                    </font>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

第六节——前台用户系统的实现

6.4.2 控制器层方法

package pers.xsc.online_shopping.controller.before;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.xsc.online_shopping.entity.User;
import pers.xsc.online_shopping.service.before.BUserService;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class BUserController {

    @Autowired
    private BUserService bUserService;

    @RequestMapping("/toRegister")
    public String toRegister(@ModelAttribute("user") User user) {
        return "user/register";
    }

    @RequestMapping("/register")
    public String register(@ModelAttribute("user") @Validated User user, BindingResult rs) {
        if(rs.hasErrors()){//验证失败
            return "user/register";
        }
        return bUserService.register(user);
    }
    @RequestMapping("/isUse")
    @ResponseBody
    public String isUse(@RequestBody User user) {
        return bUserService.isUse(user);
    }

    @RequestMapping("/toLogin")
    public String toLogin(@ModelAttribute("user") User user) {
        //@ModelAttribute("user")与th:object="${user}"相对应
        return "user/login";
    }
    @RequestMapping("/login")
    public String login(@ModelAttribute("user") User user,
                        BindingResult rs, HttpSession session, Model model) {
        if(rs.hasErrors()){//验证失败
            return "user/login";
        }
        return bUserService.login(user, session, model);
    }


}

6.4.3 业务层接口及实现

package pers.xsc.online_shopping.service.before;

import org.springframework.ui.Model;
import pers.xsc.online_shopping.entity.User;

import javax.servlet.http.HttpSession;

public interface BUserService {
    public String register(User user);

    String isUse(User user);

    public String login(User user, HttpSession session, Model model);

}
package pers.xsc.online_shopping.service.before.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import pers.xsc.online_shopping.entity.User;
import pers.xsc.online_shopping.mapper.before.BUserMapper;
import pers.xsc.online_shopping.service.before.BUserService;
import pers.xsc.online_shopping.utils.MD5Utils;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service
public class BUserServiceImpl implements BUserService {
    @Autowired
    BUserMapper bUserMapper;

    @Override
    public String register(User user) {
        //对密码MD5加密
        user.setPwd(MD5Utils.getMD5StrByDigestUtils(user.getPwd()));
        user.setRtime(new Date());
        user.setUtime(new Date());
        if( bUserMapper.register(user) > 0) {
            return "user/login";
        }
        return "user/register";
    }
    @Override
    public String isUse(User user) {
        if(bUserMapper.isUse(user).size() > 0) {
            return "no";
        }
        return "ok";
    }
    @Override
    public String login(User user, HttpSession session, Model model) {
        //对密码MD5加密
        user.setPwd(MD5Utils.getMD5StrByDigestUtils(user.getPwd()));
        String rand = (String)session.getAttribute("rand");
        if(!rand.equalsIgnoreCase(user.getCode())) {
            model.addAttribute("errorMessage", "验证码错误!");
            return "user/login";
        }
        List<User> list = bUserMapper.login(user);
        if(list.size() > 0) {
            session.setAttribute(Constant.CURRENT_USER, list.get(0));
            return "redirect:/";//到首页
        }
        model.addAttribute("errorMessage", "用户名或密码错误!");
        return "user/login";
    }

}

6.4.4 持久层

package pers.xsc.online_shopping.mapper.before;

import org.apache.ibatis.annotations.Param;
import pers.xsc.online_shopping.entity.User;

import java.util.Collection;
import java.util.List;

public interface BUserMapper {
    public int register(User user);

    public List<User> isUse(User user);

    public List<User> login(User user);


}

6.4.5 映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="pers.xsc.online_shopping.mapper.before.BUserMapper">
    <insert id="register" parameterType="pers.xsc.online_shopping.entity.User">
        insert into user_table (id, email, pwd,rtime,utime)  values(null, #{email}, #{pwd}, #{rtime}, #{utime})
    </insert>

    <select id="isUse" parameterType="pers.xsc.online_shopping.entity.User" resultType="pers.xsc.online_shopping.entity.User">
        select * from user_table where email = #{email}
    </select>
    <select id="login" resultType="pers.xsc.online_shopping.entity.User">
        select * from user_table where email = #{email} and pwd = #{pwd}
    </select>
</mapper>

6.5 商品收藏及查看我的收藏

6.5.1 视图层页面

【src/main/resources/templates/user/myFocus.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>收藏页面</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
</head>
<body>
<div th:include="user/header"></div>
<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">收藏列表</h3>
        </div>
        <div class="panel-body">
            <div class="table table-responsive">
                <table class="table table-bordered table-hover">
                    <tbody class="text-center">
                        <tr>
                            <th>商品图片</th>
                            <th>商品名称</th>
                            <th>原价</th>
                            <th>现价</th>
                        </tr>
                        <tr th:each="focus:${myFocus}">
                            <td>
                                <a th:href="'goodsDetail?id=' + ${focus.id}"> 
                                <img th:src="'images/' + ${focus.gpicture}"
                                    style="height: 50px; width: 50px; display: block;">
                                </a>
                            </td>
                            <td th:text="${focus.gname}"></td>
                            <td th:text="${focus.goprice}"></td>
                            <td th:text="${focus.grprice}"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>

第六节——前台用户系统的实现

6.5.2 控制器层方法

package pers.xsc.online_shopping.controller.before;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.xsc.online_shopping.entity.Goods;
import pers.xsc.online_shopping.exception.CustomException;
import pers.xsc.online_shopping.exception.ExceptionEnum;
import pers.xsc.online_shopping.service.before.FocusService;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/focus")
public class FocusController {
    @Autowired
    FocusService focusService ;
    @RequestMapping("/myFocus")
    public String myFocus(Model model, HttpSession session) {
        return focusService.myFocus(model, session);
    }

    @RequestMapping("/focus")
    @ResponseBody
    public String focus(@RequestBody Goods goods, Model model, HttpSession session) {
        return focusService.focus(model, session, goods.getId());
    }
}

6.5.3 业务层接口及实现

package pers.xsc.online_shopping.service.before;

import org.springframework.ui.Model;

import javax.servlet.http.HttpSession;

public interface FocusService {
    String focus(Model model, HttpSession session, Integer gid);

    public String myFocus(Model model, HttpSession session);
}
package pers.xsc.online_shopping.service.before.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import pers.xsc.online_shopping.entity.User;
import pers.xsc.online_shopping.mapper.before.FocusMapper;
import pers.xsc.online_shopping.mapper.before.IndexMapper;
import pers.xsc.online_shopping.service.before.FocusService;
import pers.xsc.online_shopping.utils.Constant;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Service
public class FoucsServiceImpl implements FocusService {
    @Autowired
    FocusMapper focusMapper;

    @Autowired
    IndexMapper indexMapper;

    /**
     * 收藏商品
     * @param model
     * @param session
     * @param gid
     * @return
     */
    @Override
    public String focus(Model model, HttpSession session, Integer gid) {
        User user = (User)session.getAttribute(Constant.CURRENT_USER);
        Integer uid = user.getId();
        List<Map<String,Object>> list = focusMapper.isFocus(uid, gid);
        //判断是否已收藏
        if(list.size() > 0) {
            return "no";
        }else {
            focusMapper.focus(uid, gid);
            return "ok";
        }
    }

    /**
     * 查看我的收藏
     * @param model
     * @param session
     * @return
     */
    @Override
    public String myFocus(Model model, HttpSession session) {
        //广告区商品
        model.addAttribute("advertisementGoods", indexMapper.selectAdvertisementGoods());
        //导航栏商品类型
        model.addAttribute("goodsType", indexMapper.selectGoodsType());
        User user = (User)session.getAttribute(Constant.CURRENT_USER);
        model.addAttribute("myFocus", focusMapper.myFocus(user.getId()));
        return "user/myFocus";
    }
}

6.5.4 持久层

package pers.xsc.online_shopping.mapper.before;

import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface FocusMapper {
    public List<Map<String,Object>> isFocus(@Param("uid") Integer uid, @Param("gid") Integer gid);
    public int focus(@Param("uid") Integer uid, @Param("gid") Integer gid);
    public List<Map<String,Object>> myFocus(Integer uid);
}

6.5.5 映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="pers.xsc.online_shopping.mapper.before.FocusMapper">
    <!-- 处理加入收藏  -->
    <select id="isFocus" resultType="map">
        select * from focus_table where goodstable_id = #{gid} and usertable_id = #{uid}
    </select>
    <insert id="focus">
        insert into focus_table (id, goodstable_id, usertable_id, ftime)  values(null, #{gid}, #{uid}, now())
    </insert>
    <!-- 我的收藏 -->
    <select id="myFocus" resultType="map"  parameterType="Integer">
        select gt.id, gt.gname, gt.goprice, gt.grprice, gt.gpicture from focus_table ft, goods_table gt
        where ft.goodstable_id=gt.id and  ft.usertable_id = #{uid}
    </select>
</mapper>

6.6 商品加入购物车及查看我的购物车

6.6.1 视图层页面

【src/main/resources/templates/user/cart.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>购物车页面</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
    function deleteCart(obj){
        if(window.confirm("确认删除吗?")){
            //获取路径
            window.location.href = "/cart/deleteCart?gid=" +  obj;
        }
    }
    function clearCart(){
        if(window.confirm("确认清空吗?")){

            window.location.href = "/cart/clearCart";
        }
    }
</script>
</head>
<body>
<div th:include="user/header"></div>
<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">购物车列表</h3>
        </div>
        <div class="panel-body">
            <div class="table table-responsive">
                <table class="table table-bordered table-hover">
                    <tbody class="text-center">
                        <tr>
                            <th>商品信息</th>
                            <th>单价(元)</th>
                            <th>数量</th>
                            <th>小计</th>
                            <th>操作</th>
                        </tr>
                        <tr th:each="cart:${cartlist}">
                            <td>
                                <a th:href="'goodsDetail?id=' + ${cart.id}"> 
                                <img th:src="'images/' + ${cart.gpicture}"
                                    style="height: 50px; width: 50px; display: block;">
                                </a>
                            </td>
                            <td th:text="${cart.grprice}"></td>
                            <td th:text="${cart.shoppingnum}"></td>
                            <td th:text="${cart.smallsum}"></td>
                            <td>
                                <a th:href="'javascript:deleteCart('+${cart.id}+')'" >删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="5">
                            <font style="color: #a60401; font-size: 13px; font-weight: bold; letter-spacing: 0px;">
                                购物金额总计(不含运费) ¥&nbsp;<span th:text="${total}"></span>元
                            </font>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="5">
                                <a href="javascript:clearCart()" >清空购物车</a>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="5">
                                <a href="cart/selectCart?act=toCount" >去结算</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>

第六节——前台用户系统的实现

6.6.2 控制器层方法

package pers.xsc.online_shopping.controller.before;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.xsc.online_shopping.entity.Goods;
import pers.xsc.online_shopping.entity.Order;
import pers.xsc.online_shopping.mapper.before.CartMapper;
import pers.xsc.online_shopping.service.before.CartService;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    CartService cartService;
    //我的购物车
    @RequestMapping("/selectCart")
    public String selectCart(Model model, HttpSession session, String act) {
        return cartService.selectCart(model, session, act);
    }
    //添加购物车
    @RequestMapping("/putCart")
    public String putCart(Goods goods, Model model, HttpSession session) {
        return cartService.putCart(goods, model, session);
    }
    //清空购物车
    @RequestMapping("/clearCart")
    public String clearCart(HttpSession session) {
        return cartService.clearCart(session);
    }
    //购物车删除商品
    @RequestMapping("/deleteCart")
    public String deleteCart(HttpSession session, Integer gid) {
        return cartService.deleteCart(session, gid);
    }

}

6.6.3 业务层接口及实现

package pers.xsc.online_shopping.service.before;

import org.springframework.ui.Model;
import pers.xsc.online_shopping.entity.Goods;
import pers.xsc.online_shopping.entity.Order;

import javax.servlet.http.HttpSession;

public interface CartService {
    public String selectCart(Model model, HttpSession session, String act);
    public String putCart(Goods goods, Model model, HttpSession session);
    public String clearCart(HttpSession session);
    public String deleteCart(HttpSession session, Integer gid);

}
package pers.xsc.online_shopping.service.before.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import pers.xsc.online_shopping.entity.Goods;
import pers.xsc.online_shopping.entity.Order;
import pers.xsc.online_shopping.entity.User;
import pers.xsc.online_shopping.mapper.before.BOrderMapper;
import pers.xsc.online_shopping.mapper.before.CartMapper;
import pers.xsc.online_shopping.mapper.before.IndexMapper;
import pers.xsc.online_shopping.service.before.CartService;
import pers.xsc.online_shopping.utils.Constant;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    CartMapper cartMapper;

    @Autowired
    IndexMapper indexMapper;



    @Override
    public String selectCart(Model model, HttpSession session, String act) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        List<Map<String, Object>> list = cartMapper.selectCart(user.getId());
        double sum = 0;
        for (Map<String, Object> map : list) {
            sum = sum + (Double)map.get("smallsum");
        }
        model.addAttribute("total", sum);
        model.addAttribute("cartlist", list);
        //广告区商品
        model.addAttribute("advertisementGoods", indexMapper.selectAdvertisementGoods());
        //导航栏商品类型
        model.addAttribute("goodsType", indexMapper.selectGoodsType());
        if("toCount".equals(act)) {//去结算页面
            return "user/count";
        }
        return "user/cart";
    }

    @Override
    public String putCart(Goods goods, Model model, HttpSession session) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        Integer uid = user.getId();
        //如果商品已在购物车,只更新购买数量
        if(cartMapper.isPutCart(uid, goods.getId()).size() > 0) {
            cartMapper.updateCart(uid, goods.getId(), goods.getBuyNumber());
        }else {//新增到购物车
            cartMapper.putCart(uid, goods.getId(), goods.getBuyNumber());
        }
        //跳转到查询购物车
        return "forward:/cart/selectCart";
    }
    @Override
    public String clearCart(HttpSession session) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        Integer uid = user.getId();
        cartMapper.clear(uid);
        return "forward:/cart/selectCart";
    }

    @Override
    public String deleteCart(HttpSession session, Integer gid) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        Integer uid = user.getId();
        cartMapper.deleteAgoods(uid, gid);
        return "forward:/cart/selectCart";
    }


}

6.6.4 持久层

package pers.xsc.online_shopping.mapper.before;

import org.apache.ibatis.annotations.Param;
import org.springframework.ui.Model;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

public interface CartMapper {
    public List<Map<String,Object>> selectCart(Integer uid);
    public int putCart(@Param("uid") Integer uid,
                       @Param("gid") Integer gid,
                       @Param("bnum") Integer bnum);
    public List<Map<String,Object>>  isPutCart(@Param("uid") Integer uid, @Param("gid") Integer gid);
    public int updateCart(@Param("uid") Integer uid,
                          @Param("gid") Integer gid,
                          @Param("bnum") Integer bnum);
    public int clear(Integer uid);
    public int deleteAgoods(@Param("uid") Integer uid, @Param("gid") Integer gid);

}

6.6.5 映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="pers.xsc.online_shopping.mapper.before.CartMapper">
    <!-- 查询购物车 -->
    <select id="selectCart" parameterType="Integer" resultType="map">
        select gt.id, gt.gname, gt.gpicture, gt.grprice, ct.shoppingnum, ct.shoppingnum*gt.grprice smallsum
        from goods_table gt, cart_table ct where gt.id=ct.goodstable_id and ct.usertable_id=#{uid}
    </select>
    <!-- 是否已添加购物车 -->
    <select id="isPutCart" resultType="map">
        select * from cart_table where goodstable_id=#{gid}  and usertable_id=#{uid}
    </select>
    <!-- 添加购物车 -->
    <insert id="putCart">
        insert into cart_table (id, usertable_id, goodstable_id, shoppingnum) values(null, #{uid},#{gid},#{bnum})
    </insert>
    <!-- 更新购物车 -->
    <update id="updateCart">
        update cart_table set shoppingnum=shoppingnum+#{bnum} where usertable_id=#{uid} and goodstable_id=#{gid}
    </update>
    <!-- 清空购物车 -->
    <delete id="clear" parameterType="Integer">
        delete from cart_table where usertable_id=#{uid}
    </delete>
    <!-- 删除购物车 -->
    <delete id="deleteAgoods">
        delete from cart_table where usertable_id=#{uid} and goodstable_id=#{gid}
    </delete>
</mapper>

6.7 购物车结算及查看我的订单

6.7.1 视图层页面

【src/main/resources/templates/user/count.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>结算页面</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
</head>
<body>
<div th:include="user/header"></div>
<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">购物车列表</h3>
        </div>
        <div class="panel-body">
            <div class="table table-responsive">
                <table class="table table-bordered table-hover">
                    <tbody class="text-center">
                        <tr>
                            <th>商品信息</th>
                            <th>单价(元)</th>
                            <th>数量</th>
                            <th>小计</th>
                        </tr>
                        <tr th:each="cart:${cartlist}">
                            <td>
                                <a th:href="'goodsDetail?id=' + ${cart.id}"> 
                                <img th:src="'images/' + ${cart.gpicture}"
                                    style="height: 50px; width: 50px; display: block;">
                                </a>
                            </td>
                            <td th:text="${cart.grprice}"></td>
                            <td th:text="${cart.shoppingnum}"></td>
                            <td th:text="${cart.smallsum}"></td>
                        </tr>
                        <tr>
                            <td colspan="4">
                            <font style="color: #a60401; font-size: 13px; font-weight: bold; letter-spacing: 0px;">
                                购物金额总计(不含运费) ¥&nbsp;<span th:text="${total}"></span>元
                            </font>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4">
                                <a th:href="'border/submitOrder?amount=' + ${total}" >提交订单</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>

第六节——前台用户系统的实现 【src/main/resources/templates/user/pay.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>支付页面</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script src="js/jquery.min.js"></script>
<script type="text/javascript" th:inline="javascript">
    function pay(){
            $.ajax(
                {
                    //请求路径,要注意的是url和th:inline="javascript"
                    url : [[@{/border/pay}]],
                    //请求类型
                    type : "post",
                    contentType : "application/json",
                    //data表示发送的数据
                    data : JSON.stringify({
                        id : $("#oid").text()
                    }),
                    //成功响应的结果
                    success : function(obj){//obj响应数据
                        alert("支付成功");
                        window.location.href = '/';
                    },
                    error : function() {
                        alert("处理异常!");
                    }
                }    
            );
    }
</script>
</head>
<body>
<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">订单提交成功</h3>
        </div>
        <div class="panel-body">
            <div>
                您的订单编号为<font color="red" size="5"> <span id="oid" th:text="${order.id}"></span></font>    。<br><br>
                <a href="javascript:pay()">去支付</a>
            </div>
        </div>
    </div>
</div>
</body>
</html>

第六节——前台用户系统的实现 【src/main/resources/templates/user/myOrder.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>订单页面</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script src="js/jquery.min.js"></script>
<script type="text/javascript" th:inline="javascript">
    function pay(){
            $.ajax(
                {
                    //请求路径,要注意的是url和th:inline="javascript"
                    url : [[@{/border/pay}]],
                    //请求类型
                    type : "post",
                    contentType : "application/json",
                    //data表示发送的数据
                    data : JSON.stringify({
                        id : $("#oid").text()
                    }),
                    //成功响应的结果
                    success : function(obj){//obj响应数据
                        alert("支付成功");
                        window.location.href = '/';
                    },
                    error : function() {
                        alert("处理异常!");
                    }
                }    
            );
    }
</script>
</head>
<body>
<div th:include="user/header"></div>
<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">订单列表</h3>
        </div>
        <div class="panel-body">
            <div class="table table-responsive">
                <table class="table table-bordered table-hover">
                    <tbody class="text-center">
                        <tr>
                            <th>订单编号</th>
                            <th>订单金额</th>
                            <th>订单状态</th>
                            <th>下单时间</th>
                            <th>查看详情</th>
                        </tr>
                        <tr th:each="order:${myOrder}">
                            <td> <span id="oid" th:text="${order.id}"></span></td>
                            <td th:text="${order.amount}"></td>
                            <td>
                                <span th:if="${order.status} == 0" >
                                    未支付 &nbsp; <a href="javascript:pay()" >去支付</a>
                                </span>
                                <span th:if="${order.status} == 1" >
                                    已支付
                                </span>
                            </td>
                            <td th:text="${order.otime}"></td>
                            <td>
                                <a th:href="'border/orderDetail?id=' + ${order.id}" target="_blank">查看详情</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>

第六节——前台用户系统的实现 【src/main/resources/templates/user/orderDetail.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>订单详情页面</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
</head>
<body>
<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">订单详情</h3>
        </div>
        <div class="panel-body">
            <div class="table table-responsive">
                <table class="table table-bordered table-hover">
                    <tbody class="text-center">
                        <tr>
                            <th>商品编号</th>
                            <th>商品图片</th>
                            <th>商品名称</th>
                            <th>商品购买价</th>
                            <th>购买数量</th>
                        </tr>
                        <tr th:each="od:${orderDetail}">
                            <td th:text="${od.id}"></td>
                            <td>
                                <a th:href="'goodsDetail?id=' + ${od.id}"> 
                                <img th:src="'images/' + ${od.gpicture}"
                                    style="height: 50px; width: 50px; display: block;">
                                </a>
                            </td>
                            <td th:text="${od.gname}"></td>
                            <td th:text="${od.grprice}"></td>
                            <td th:text="${od.shoppingnum}"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>

第六节——前台用户系统的实现

6.7.2 控制器层方法

package pers.xsc.online_shopping.controller.before;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.xsc.online_shopping.entity.Order;
import pers.xsc.online_shopping.service.before.BOrderService;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/border")
public class BOrderController {
    @Autowired
    BOrderService bOrderService;

    //结算
    @RequestMapping("/pay")
    @ResponseBody
    public String pay(@RequestBody Order order) {
        return bOrderService.pay(order);
    }

    //提交订单
    @RequestMapping("/submitOrder")
    public String submitOrder(Order order, Model model, HttpSession session) {
        return bOrderService.submitOrder(order, model, session);
    }
    //查看我的订单
    @RequestMapping("/myOder")
    public String myOder(Model model, HttpSession session) {
        return bOrderService.myOder(model, session);
    }
    //订单详情
    @RequestMapping("/orderDetail")
    public String orderDetail(Model model, Integer id) {
        return bOrderService.orderDetail(model, id);
    }
}

6.7.3 业务层接口

package pers.xsc.online_shopping.service.before;

import org.springframework.ui.Model;
import pers.xsc.online_shopping.entity.Order;

import javax.servlet.http.HttpSession;

public interface BOrderService {
    //支付
    public String pay(Order order);
    //提交订单
    public String submitOrder(Order order, Model model, HttpSession session);
    //查看我的订单
    public String myOder(Model model, HttpSession session);
    //查看订单详情
    public String orderDetail(Model model, Integer id);
}
package pers.xsc.online_shopping.service.before.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import pers.xsc.online_shopping.entity.Order;
import pers.xsc.online_shopping.entity.User;
import pers.xsc.online_shopping.mapper.before.BOrderMapper;
import pers.xsc.online_shopping.mapper.before.CartMapper;
import pers.xsc.online_shopping.mapper.before.IndexMapper;
import pers.xsc.online_shopping.service.before.BOrderService;
import pers.xsc.online_shopping.utils.Constant;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Service
public class BOrderServiceImpl implements BOrderService {
    @Autowired
    BOrderMapper bOrderMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    IndexMapper indexMapper;
    //订单支付
    @Override
    public String pay(Order order) {
        bOrderMapper.pay(order.getId());
            return "ok";


    }
    //提交订单
    @Override
    @Transactional
    public String submitOrder(Order order, Model model, HttpSession session) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        order.setUsertable_id(user.getId());
        //生成订单
        bOrderMapper.addOrder(order);
        //生成订单详情
        bOrderMapper.addOrderDetail(order.getId(), user.getId());
        //减少商品库存
        List<Map<String,Object>> listGoods =  bOrderMapper.selectGoodsShop(user.getId());
        for (Map<String, Object> map : listGoods) {
            bOrderMapper.updateStore(map);
        }
        //清空购物车
        cartMapper.clear(user.getId());
        model.addAttribute("order", order);
        return "user/pay";
    }
    //查看我的订单
    @Override
    public String myOder(Model model, HttpSession session) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        //广告区商品
        model.addAttribute("advertisementGoods", indexMapper.selectAdvertisementGoods());
        //导航栏商品类型
        model.addAttribute("goodsType", indexMapper.selectGoodsType());
        model.addAttribute("myOrder", bOrderMapper.myOrder(user.getId()));
        return "user/myOrder";
    }
    //查看订单详情
    @Override
    public String orderDetail(Model model, Integer id) {
        model.addAttribute("orderDetail", bOrderMapper.orderDetail(id));
        return "user/orderDetail";
    }
}

6.7.4 持久层

package pers.xsc.online_shopping.mapper.before;

import org.apache.ibatis.annotations.Param;
import pers.xsc.online_shopping.entity.Order;

import java.util.List;
import java.util.Map;

public interface BOrderMapper {
    public int pay(Integer ordersn);
    public int addOrder(Order order);
    public int addOrderDetail(@Param("ordersn") Integer ordersn, @Param("uid") Integer uid);
    public List<Map<String,Object>> selectGoodsShop(Integer uid);
    public int updateStore(Map<String,Object> map);
    public List<Map<String,Object>> myOrder(Integer uid);
    public List<Map<String,Object>> orderDetail(Integer id);
}

6.7.5 映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="pers.xsc.online_shopping.mapper.before.BOrderMapper">

    <!-- 添加一个订单,成功后将主键值回填给id(实体类的属性)-->
    <insert id="addOrder" parameterType="pers.xsc.online_shopping.entity.Order" keyProperty="id" useGeneratedKeys="true">
        insert into orderbase_table (usertable_id, amount, status, otime) values (#{usertable_id}, #{amount}, 0, now())
    </insert>
    <!-- 生成订单详情 -->
    <insert id="addOrderDetail">
        insert into orderdetail_table (orderbasetable_id, goodstable_id, SHOPPINGNUM) select #{ordersn}, goodstable_id, SHOPPINGNUM from CART_TABLE where usertable_id = #{uid}
    </insert>
    <!-- 查询商品购买量,以便更新库存使用 -->
    <select id="selectGoodsShop"  parameterType="Integer" resultType="map">
        select shoppingnum gshoppingnum, goodstable_id gid from cart_table where usertable_id=#{uid}
    </select>
    <!-- 我的订单 -->
    <select id="myOrder"  resultType="map" parameterType="Integer">
        select id, amount, usertable_id, status, otime  from ORDERBASE_TABLE where usertable_id = #{uid}
    </select>
    <!-- 更新商品库存 -->
    <update id="updateStore" parameterType="map">
        update GOODS_TABLE set GSTORE=GSTORE-#{gshoppingnum} where id=#{gid}
    </update>
    <!-- 支付订单 -->
    <update id="pay" parameterType="Integer">
        update orderbase_table set status=1 where id=#{ordersn}
    </update>
    <!-- 订单详情 -->
    <select id="orderDetail" resultType="map"  parameterType="Integer">
        select gt.id, gt.gname, gt.goprice, gt.grprice, gt.gpicture, odt.shoppingnum from  GOODS_TABLE gt, ORDERDETAIL_table odt
        where  odt.orderbasetable_id=#{id} and gt.id=odt.goodstable_id
    </select>

</mapper>

6.8 修改密码

6.8.1 视图层页面

【src/main/resources/templates/user/userInfo.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}"><!-- 不用base就使用th:src="@{/js/jquery.min.js} -->
<meta charset="UTF-8">
<title>用户信息页面</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<body>
    <div class="container">
    <div class="bg-primary"  style="width:100%; height: 70px;padding-top: 10px;">
           <h2 align="center">修改密码</h2>
       </div>
        <br><br>
        <form action="/user/updateUpwd" name="myform" method="post" class="form-horizontal" role="form" >
            <div class="form-group has-success">
                <label class="col-sm-2 col-md-2 control-label">邮箱</label>
                <div class="col-sm-4 col-md-4">
                    <input type="text" class="form-control" readonly="readonly" name="bemail" th:value="${session.user.email}" />
                </div>
            </div>    
            <div class="form-group has-success">
                  <label class="col-sm-2 col-md-2 control-label">密码</label>
                  <div class="col-sm-4 col-md-4">
                          <input type="password" class="form-control" name="pwd" placeholder="请输入您的新密码" />
                  </div>
             </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit"class="btn btn-success" >修改密码</button>
                    <button type="reset" class="btn btn-primary" >重置</button>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

第六节——前台用户系统的实现

6.8.2 控制器层方法

@RequestMapping("/updateUpwd")
    public String updateUpwd(HttpSession session, String pwd) {
        return bUserService.updateUpwd(session, pwd);
    }

6.8.3 业务接口及实现

 String updateUpwd(HttpSession session, String pwd);
@Override
    public String updateUpwd(HttpSession session, String pwd) {
        User user = (User)session.getAttribute(Constant.CURRENT_USER);
        Integer uid = user.getId();
        bUserMapper.updateUpwd(uid, MD5Utils.getMD5StrByDigestUtils(pwd));
        return "forward:/user/toLogin";
    }

6.8.4 持久层

void updateUpwd(@Param("uid") Integer uid, @Param("pwd") String pwd);

6.8.5映射文件

<!-- 修改密码 -->
    <update id="updateUpwd">
        update user_table set pwd=#{pwd} where id=#{uid}
    </update>
点赞
收藏
评论区
推荐文章

暂无数据