SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

一、个人信息修改

(一)个人信息修改界面的编写

当用户点击带界面时,系统会从session(user)中获取用户名、密码以及uid,并显示在页面上,其中uid设置为只读,用户不可更改。在该界面,用户可以修改自己的用户名、密码以及更换头像。在用户成功修改信息后,会强制登出,重新获取session显示数据。
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

UserInformation.jsp:

<%--
  Created by IntelliJ IDEA.
  User: RH
  Date: 2021/8/8
  Time: 16:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="layui/css/layui.css"  media="all">
    <style>
        *{margin:0px;padding:0px;}
        form{
            width:80%;
            margin:30px auto;
        }
    </style>
</head>
<body>
<script src="layui/layui.js" charset="utf-8"></script>




<form class="layui-form" action="updateUserPerson" method="post" enctype="multipart/form-data" >
    <div class="layui-form-item">
        <label class="layui-form-label">uid</label>
        <div class="layui-input-block">
            <input type="text" name="uid" required  lay-verify="required"  autocomplete="off" class="layui-input" value="${sessionScope.user.uid}" readonly="readonly">
        </div>
    </div>

    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-block">
            <input type="text" name="userName" required  lay-verify="required"  autocomplete="off" class="layui-input" value="${sessionScope.user.userName}">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-block">
            <input type="text" name="userPsd" required  lay-verify="required"  autocomplete="off" class="layui-input" value="${sessionScope.user.userPsd}">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">用户头像</label>
        <div class="layui-input-block">
            <input type="file" name="ImgFile"class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <input class="layui-btn" type="submit" value="确认修改" onclick="tologin()">
        </div>
    </div>
</form>


<script type="text/javascript">

    function tologin(){
        alert("修改成功,请重新登录!")

        window.top.location.href="login.jsp";//它表示,从最上层的窗口的地址栏发送请求


    }

    layui.use(['jquery','form'], function(){
        var $ = layui.jquery;
        var form = layui.form;

        form.render();
    });
</script>
</body>
</html>

(二)个人信息修改功能的实现

当用户单击确认修改按钮时,会向后台发出updateUserPerson请求,此时在UserController中新增updateUserPerson()方法。
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

UserController :

@Controller
public class UserController {

    @Autowired
    private UserServiceI userServiceI;
    @Autowired
    private ResultMap resultMap;

    @RequestMapping("/login")
    @ResponseBody
    public ResultMap login(String userName, String userPsd, String captcha , HttpSession session) {
        try {
            int authority=userServiceI.login(userName,userPsd,captcha,session);
            resultMap.setStatus(true);
            resultMap.setAuthority(authority);
        } catch (Exception e) {
            resultMap.setStatus(false);
            resultMap.setMessage(e.getMessage());
        }
        return resultMap;
    }


    @RequestMapping("/register")
    @ResponseBody
    public ResultMap insertUserregister(String userName,String userPsd,String sex){
        try{
            userServiceI.insertUserregister(userName,userPsd,sex);
            resultMap.setStatus(true);
        }catch (Exception e){
            resultMap.setStatus(false);
            resultMap.setMessage(e.getMessage());
        }
        return resultMap;
    }

    @RequestMapping("/updateUserPerson")
    public void updateUserPerson(String uid, String userName, String userPsd, MultipartFile ImgFile, HttpSession session, HttpServletRequest request){
        session.invalidate();
        try{
            if(ImgFile.getSize()==0){
                ImgFile=null;
            }
            userServiceI.updateUserPerson(uid,userName,userPsd,ImgFile,request);
        }catch (Exception e){
            resultMap.setStatus(false);
            resultMap.setMessage(e.getMessage());
        }

    }

}

在UserController中,将会调用userServiceI,此时向UserServiceI、UserServiceImpl新增updateUserPerson()方法
UserServiceI:

public interface UserServiceI {

    public int login(String userName, String userPsd, String captcha, HttpSession session);
    
    public int insertUserregister(String userName,String userPsd,String sex);

	public int updateUserPerson(String uid, String userName, String userPsd, MultipartFile ImgFile, HttpServletRequest request);
}

UserServiceImpl:
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

@Service
public class UserServiceImpl implements UserServiceI{

    @Autowired
    private UserDao userDao;

    @Override
    public int login(String userName, String userPsd, String captcha, HttpSession session) {
        if(userName.equals("")) {
            throw new RuntimeException("用户名不能为空!");
        }
        if(userPsd.equals("")) {
            throw new RuntimeException("密码不能为空!");
        }
        if(captcha.equals("")) {
            throw new RuntimeException("验证码不能为空!");
        }

        String cap= (String) session.getAttribute("captcha");

        if(!captcha.equalsIgnoreCase(cap)){
            throw new RuntimeException("验证码有误!");
        }

        User user = new User(userName,userPsd);
        user = userDao.login(user);
        if(user == null) {
            throw new RuntimeException("用户名或密码输入有误!");
        }else {
            session.setAttribute("user",user);
        }

        return user.getAuthorityType();
    }

    @Override
    public int insertUserregister(String userName, String userPsd, String sex) {
        if(userName.equals("")) {
            throw new RuntimeException("用户名不能为空!");
        }
        if(userPsd.equals("")) {
            throw new RuntimeException("密码不能为空!");
        }


        User user =new User();
        user.setUserName(userName);
        user.setUserPsd(userPsd);
        user.setSex(sex);
        user.setImgPath("images/defaultHeadimg.png");
        user.setHeadImg("defaultHeadimg.png");
        int num=userDao.insertUser(user);
        if(num==0){
            throw new RuntimeException("新增失败!");
        }

        User getLatestId=userDao.selectLatestId();

        User_Authority user_authority=new User_Authority();
        user_authority.setUid(getLatestId.getUid());
        user_authority.setAid(3);
        num=userDao.insertUserAuthority(user_authority);
        if(num==0){
            throw new RuntimeException("新增权限失败!");
        }
        return num;
    }


    @Override
   	 public int updateUserPerson(String uid, String userName, String userPsd, MultipartFile ImgFile, HttpServletRequest request) {
        User user =new User();
        int Intuid = Integer.parseInt(uid);
        user.setUid(Intuid);
        user.setUserName(userName);
        user.setUserPsd(userPsd);
        Map<String,String> map = getimg(ImgFile,request);
        return updateUserPerson(user,map);
    }

}

在updateUserPerson()方法中,我们需要调用getimg()方法和updateUserPerson()方法。
定义getimg()方法:

SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

    private Map<String,String> getimg(MultipartFile ImgFile, HttpServletRequest request) {
        Map<String,String> map = new HashMap<String,String>();
        if(ImgFile!=null){
        //图片文件原名称
        String userImgName = ImgFile.getOriginalFilename();
        //得到图片的后缀名
        String imgFileExtension = userImgName.substring(userImgName.lastIndexOf("."));
        //生成新得图片名称: 因为上传的文件可能重名
        String newUserImgName = UUID.randomUUID().toString()+imgFileExtension;
        //获得图片要上传到服务器的路径
        String imgServerPath = request.getServletContext().getRealPath("/")+"images/"+newUserImgName;

        //创建图片目标目录
        File targetImgFile = new File(imgServerPath);
        //创建视频目标目录

        //向map中存值: 视频原名称、视频相对路径、图片相对路径
        try {
            ImgFile.transferTo(targetImgFile);//图片上传

            map.put("imgFileName", userImgName);

            //获得图片相对路径: 存入到数据库中
            String imgRelativePath = request.getServletContext().getContextPath()+"/images/"+newUserImgName;
            //获得视频相对路径: 存入到数据库中

            map.put("imgRelativePath", imgRelativePath);

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }else {
            map.put("imgFileName", null);
            map.put("imgRelativePath", null);
        }
        return map;
    }

定义updateUserPerson()方法:
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

    private int updateUserPerson(User user, Map<String,String> map) {
        user.setHeadImg(map.get("imgFileName"));
        user.setImgPath(map.get("imgRelativePath"));

        int num=userDao.updateUserPerson(user);

        if(num==0){
            throw new RuntimeException("新增失败!");
        }
        return num;
    }

当updateUserPerson()方法调用UserDao时,会调用updateUserPerson()方法,我们需要在UserDao中进行定义。
UserDao:

@Repository
public interface UserDao {

    public User login(User user);
    
    public int insertUser(User user) ;
    
    public User selectLatestId();
    
    public int insertUserAuthority(User_Authority user_authority) ;

    public int updateUserPerson(User user) ;
}

在usermapper.xml中编写sql语句
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

<?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="com.RH.db.dao.UserDao">

    <select id="login" parameterType="com.RH.db.pojo.User" resultType="com.RH.db.pojo.User">
        select u.* ,a.authorityType
        from `user` as u,user_authority as ua,authority as a
        where
        u.userName=#{userName} and u.userPsd=#{userPsd} and u.uid=ua.uid and ua.aid = a.aid
    </select>

    <insert id="insertUser" parameterType="com.RH.db.pojo.User">
        insert into `User` (userName,userPsd,sex,headImg,imgPath)values (#{userName},#{userPsd},#{sex},#{headImg},#{imgPath})
    </insert>
    
     <select id="selectLatestId" resultType="com.RH.db.pojo.User">
        select * from `user` order by uid desc limit 1;
    </select>

    <insert id="insertUserAuthority" parameterType="com.RH.db.pojo.User_Authority">
        insert into user_authority (uid,aid) values (#{uid},#{aid})
    </insert>
    
        <update id="updateUserPerson" parameterType="com.RH.db.pojo.User">
        update `User`
        <trim prefix="set" suffixOverrides=",">
            <if test="userName!=null and userName !='' ">userName=#{userName},</if>
            <if test="userPsd!=null and userPsd !='' ">userPsd=#{userPsd},</if>
            <if test="headImg!=null and headImg !='' ">headImg=#{headImg},</if>
            <if test="imgPath!=null and imgPath !='' ">imgPath=#{imgPath},</if>
        </trim>
       where uid=#{uid}
    </update>
</mapper>

至此,个人信息修改功能实现,后续员工界面和老板界面也是一样,不再重复说明。

二、点餐功能

(一)点餐功能界面的编写

当用户点击点单功能时,会向后端发送selectAllFoodByLimits请求,后端会返回菜品信息(菜品名称、菜品类别、菜品描述、菜品价格、菜品图片),显示在页面上。
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现
当用户点击订购时,会跳出菜单,用户可在菜单选择订购数量,当用户单击提交时,会将订购菜品提交到购物车中。
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现
cartTest.jsp:
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

<%--
  Created by IntelliJ IDEA.
  User: RH
  Date: 2021/8/9
  Time: 19:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>购物车测试</title>
    <link rel="stylesheet" href="layui/css/layui.css"  media="all">

    <style type="text/css">
        .layui-table-cell{
            height:auto!important;
            white-space:normal;
        }

    </style>
</head>
<body>
<script src="layui/layui.js" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述 JS 路径需要改成你本地的 -->
<%--显示表格,表格id为data_table--%>
<table class="layui-hide" id="data_table" lay-filter="FoodFilter"></table>
<%--编辑菜单--%>
<script type="text/html" id="editBar">
    <a class="layui-btn layui-btn-xs" lay-event="order">订购</a>
</script>
<script type="text/javascript">
    layui.use(['table','layer','jquery','form'], function() {
        var table = layui.table;
        var layer = layui.layer;
        var $ = layui.jquery;
        var form = layui.form;
        table.render({
            elem: '#data_table'
            , url: 'selectAllFoodByLimits'
            , toolbar: "#addBar"
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.total, //解析数据长度
                    "data": res.list //解析数据列表
                };
            }
            , cols: [[
                {field: 'foodName', title: '菜品名称'},
                {field: 'foodType', title: '菜品类别'},
                {field: 'foodDescription', title: '菜品描述'},
                {field: 'foodPrice', title: '菜品价格'},
                {field:'foodImgPath', title:"菜品图片" ,templet: '<div><img src="{{ d.foodImgPath }}" style="width:50px; height:50px;"></div>'},
                {fixed: 'right', title: '操作', toolbar: '#editBar'}	//调用script定义得两个按钮
            ]]
            , page: true	//开启分页
            , limits: [5, 10, 15, 20, 25, 30]	//自定义每页显示多少条数据
        });

        table.on('tool(FoodFilter)', function(obj){//obj代表点击的这一行所有内容,包含两个按钮和数据
            var data = obj.data; //选中的哪一行数据
            var fid = data.fid;
            console.log(obj)
            if(obj.event === 'order'){//点击修改按钮

                layer.open({
                    type:1,
                    title:"请确认选择",
                    content: $("#editPanel").html(),//利用jquery选择器获取元素里面的html内容
                    area:['400px','600px'],
                    btn: ['提交', '重置', '取消'],
                    yes: function(index, layero){
                        var formObj = form.val("editFilter");	//这是js对象,无法发送给后台
                        var jsonStr = JSON.stringify(formObj);	//将js对象转换成json格式字符串

                        $.post('orderInCart',{jsonStr:jsonStr,fid:fid},function(res){

                        },"json");

                          layer.close(index);//关闭弹框
                    },btn2: function(index, layero){
                        form.val('editFilter',{//addFilter得值对应得是 form中带有class="layui-form"得元素上 lay-filter="addFilter"
                            foodName:data.foodName,
                            tid:data.tid,
                            foodDescription:data.foodDescription,
                            foodPrice:data.foodPrice,
                            orderNum:1
                        });
                        return false; //不关闭窗口
                    },btn3: function(index, layero){
                    },success: function(index, layero){
                        //打开修改按钮,显示的面板中应该有所有视频分类,并且默认选择当前视频的类别
                        //利用ajax请求数据,将数据动态写入到select标签中
                        $.ajaxSettings.async = false;//设置ajax为同步状态,只有ajax彻底执行结束,再加载其他内容
                        $.post('selectFoodType',{},function(result){
                            if(result.status){
                                var html = '';
                                var list = result.list;
                                for(var i = 0;i<list.length;i++){
                                    html+='<option value="'+list[i].tid+'">'+list[i].foodType+'</option>';
                                }
                                $("select").append(html);
                            }else{
                                layer.msg(result.message);
                            }
                        },"json");
                        form.val('editFilter',{//addFilter得值对应得是 form中带有class="layui-form"得元素上 lay-filter="addFilter"
                            foodName:data.foodName,
                            tid:data.tid,
                            foodDescription:data.foodDescription,
                            foodPrice:data.foodPrice
                        });
                        //当form表单中出现: 单选框、多选框、下拉菜单、文本域等组件时,是不会显示出来的
                        form.render();
                    }
                });


            }

        });


    });
</script>


<script type="text/html" id="editPanel">
    <form class="layui-form" lay-filter="editFilter">


        <div class="layui-form-item">
            <label class="layui-form-label">uid</label>
            <div class="layui-input-inline">
                <input type="text" name="uid"  class="layui-input" readonly="readonly" value="${sessionScope.user.uid}">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-inline">
                <input type="text" name="userName"  class="layui-input" readonly="readonly" value="${sessionScope.user.userName}">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">菜品名称</label>
            <div class="layui-input-inline">
                <input type="text" name="foodName"  class="layui-input" readonly="readonly">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">菜品类别</label>
            <div class="layui-input-inline">
                <select name="tid" lay-verify="required" readonly="readonly"></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">菜品描述</label>
            <div class="layui-input-inline">
                <input type="text" name="foodDescription"  class="layui-input" readonly="readonly">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">菜品价格</label>
            <div class="layui-input-inline">
                <input type="text" name="foodPrice"  class="layui-input" readonly="readonly">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">菜品数量</label>
            <div class="layui-input-inline">
                <input type="text" name="orderNum"  class="layui-input" placeholder="请输入订购数量">
            </div>
        </div>
    </form>
</script>
</body>
</html>

(二)点餐功能的实现

(1)菜品显示
新建Food类:

public class Food {

    private int fid;
    private String foodName;
    private String foodDescription;
    private Double foodPrice;
    private String foodImg;
    private String foodImgPath;


    private int tid;
    private String foodType;

    private int ftid;


    public int getTid() {
        return tid;
    }

    public void setTid(int tid) {
        this.tid = tid;
    }

    public String getFoodType() {
        return foodType;
    }

    public void setFoodType(String foodType) {
        this.foodType = foodType;
    }

    public int getFtid() {
        return ftid;
    }

    public void setFtid(int ftid) {
        this.ftid = ftid;
    }

    public int getFid() {
        return fid;
    }

    public void setFid(int fid) {
        this.fid = fid;
    }

    public String getFoodName() {
        return foodName;
    }

    public void setFoodName(String foodName) {
        this.foodName = foodName;
    }

    public String getFoodDescription() {
        return foodDescription;
    }

    public void setFoodDescription(String foodDescription) {
        this.foodDescription = foodDescription;
    }

    public Double getFoodPrice() {
        return foodPrice;
    }

    public void setFoodPrice(Double foodPrice) {
        this.foodPrice = foodPrice;
    }

    public String getFoodImg() {
        return foodImg;
    }

    public void setFoodImg(String foodImg) {
        this.foodImg = foodImg;
    }

    public String getFoodImgPath() {
        return foodImgPath;
    }

    public void setFoodImgPath(String foodImgPath) {
        this.foodImgPath = foodImgPath;
    }
}

新建FoodController类,编写selectAllFoodByLimits()方法。
FoodController:
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

@Controller
public class FoodController {

    @Autowired
    private FoodServiceI foodServiceI;
    @Autowired
    private ResultMap resultMap;

    @RequestMapping("/selectAllFoodByLimits")
    @ResponseBody
    public ResultMap selectAllFoodByLimits(int page,int limit){
        try{
            PageHelper.startPage(page, limit);//开启分页
            List<Food> list=foodServiceI.selectAllFoodByLimits();
            PageInfo<Food> pageInfo=new PageInfo<Food>(list);
            long total=pageInfo.getTotal();
            resultMap.setCode(0);
            resultMap.setList(list);
            resultMap.setTotal(total);
        }catch (Exception e){
            resultMap.setCode(1);
            resultMap.setMessage(e.getMessage());
        }
        return resultMap;
    }
}

编写FoodServiceI、FoodServiceImpl。
FoodServiceI:

public interface FoodServiceI {

    public List<Food> selectAllFoodByLimits();

}

FoodServiceImpl:

@Service
public class FoodServiceImpl implements FoodServiceI{

    @Autowired
    private FoodDao foodDao;

    @Override
    public List<Food> selectAllFoodByLimits() {
        return foodDao.selectAllFoodByLimits();
    }

}

编写FoodDao。
FoodDao:

@Repository
public interface FoodDao {

    public List<Food> selectAllFoodByLimits();
    
}

编写foodmapper.xml:
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

<?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="com.RH.db.dao.FoodDao">
    <select id="selectAllFoodByLimits" resultType="com.RH.db.pojo.Food">
        select f.*,t.foodType,t.tid
        from Food as f, `type` as t, food_type as ft
        where f.fid=ft.fid and ft.tid=t.tid
    </select>
</mapper>

接下来需要单独获取菜品种类,在FoodController新增selectFoodType()方法,新建Food_Type类。
Food_Type类:

public class Food_Type {

    private String tid;
    private String foodType;

    public String getTid() {
        return tid;
    }

    public void setTid(String tid) {
        this.tid = tid;
    }

    public String getFoodType() {
        return foodType;
    }

    public void setFoodType(String foodType) {
        this.foodType = foodType;
    }
}

FoodController:

@Controller
public class FoodController {

    @Autowired
    private FoodServiceI foodServiceI;
    @Autowired
    private ResultMap resultMap;

    @RequestMapping("/selectAllFoodByLimits")
    @ResponseBody
    public ResultMap selectAllFoodByLimits(int page,int limit){
        try{
            PageHelper.startPage(page, limit);//开启分页
            List<Food> list=foodServiceI.selectAllFoodByLimits();
            PageInfo<Food> pageInfo=new PageInfo<Food>(list);
            long total=pageInfo.getTotal();
            resultMap.setCode(0);
            resultMap.setList(list);
            resultMap.setTotal(total);
        }catch (Exception e){
            resultMap.setCode(1);
            resultMap.setMessage(e.getMessage());
        }
        return resultMap;
    }

    @RequestMapping("/selectFoodType")
    @ResponseBody
    public ResultMap selectAllType() {
        try {
            List<Food_Type> list = foodServiceI.selectFoodTyprByLimits();
            resultMap.setStatus(true);
            resultMap.setList(list);
        } catch (Exception e) {
            resultMap.setStatus(false);
            resultMap.setMessage(e.getMessage());
        }
        return resultMap;
    }


}

之后在FoodServiceI、FoodServiceImpl新增selectFoodTyprByLimits()方法:
FoodServiceI:

public interface FoodServiceI {

    public List<Food> selectAllFoodByLimits();

	public List<Food_Type> selectFoodTyprByLimits();

}

FoodServiceImpl:

@Service
public class FoodServiceImpl implements FoodServiceI{

    @Autowired
    private FoodDao foodDao;

    @Override
    public List<Food> selectAllFoodByLimits() {
        return foodDao.selectAllFoodByLimits();
    }

    @Override
    public List<Food_Type> selectFoodTyprByLimits() {
        return foodDao.selectFoodTyprByLimits();
    }
}

FoodDao:

@Repository
public interface FoodDao {

    public List<Food> selectAllFoodByLimits();

    public List<Food_Type> selectFoodTyprByLimits();

}

foodmapper.xml

<?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="com.RH.db.dao.FoodDao">
    <select id="selectAllFoodByLimits" resultType="com.RH.db.pojo.Food">
        select f.*,t.foodType,t.tid
        from Food as f, `type` as t, food_type as ft
        where f.fid=ft.fid and ft.tid=t.tid
    </select>

    <select id="selectFoodTyprByLimits" resultType="com.RH.db.pojo.Food_Type">
        select * from `type`
    </select>

</mapper>

此时即可将所有菜品显示在前端。
接下来需要实现将所点菜品提交到购物车中,新建OrderController类,编写addCartItem()方法。
OrderController:

@Controller
public class OrderController {

    @Autowired
    private OrderServiceI orderServiceI;
    @Autowired
    private ResultMap resultMap;


    @RequestMapping("/orderInCart")
    public ResultMap addCartItem(String jsonStr,String fid, HttpServletRequest request) {
        try{
            orderServiceI.addCartItem(jsonStr,fid,request);
            resultMap.setStatus(true);
        }catch (Exception e){
            resultMap.setStatus(false);
            resultMap.setMessage(e.getMessage());
        }

        return resultMap;
    }

}

新建OrderService、OrderServiceImpl。由于我们点单是将,所点菜品存到购物车中,再由购物车进行提交,所以先不用操作数据库,DAO层之后再建。
OrderService:

public interface OrderServiceI {

    void addCartItem(String jsonStr,String fid, HttpServletRequest request) ;
    
}

新建Order_Detils 类:

public class Order_Detils {

    private int odid;
    private int oid;
    private int fid;
    private int uid;
    private String foodName;
    private Double foodPrice;
    private int orderNum;

    private String userName;

    private Double totalMoney;

    public int getOdid() {
        return odid;
    }

    public void setOdid(int odid) {
        this.odid = odid;
    }

    public int getOid() {
        return oid;
    }

    public void setOid(int oid) {
        this.oid = oid;
    }

    public int getFid() {
        return fid;
    }

    public void setFid(int fid) {
        this.fid = fid;
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getFoodName() {
        return foodName;
    }

    public void setFoodName(String foodName) {
        this.foodName = foodName;
    }

    public Double getFoodPrice() {
        return foodPrice;
    }

    public void setFoodPrice(Double foodPrice) {
        this.foodPrice = foodPrice;
    }

    public int getOrderNum() {
        return orderNum;
    }

    public void setOrderNum(int orderNum) {
        this.orderNum = orderNum;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Double getTotalMoney() {
        return totalMoney;
    }

    public void setTotalMoney(Double totalMoney) {
        this.totalMoney = totalMoney;
    }
}

OrderServiceImpl:
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

@Service
public class OrderServiceImpl implements OrderServiceI{

    @Override
    public void addCartItem(String jsonStr,String fid,HttpServletRequest request) {

        Order_Detils order_detils = JSON.parseObject(jsonStr, Order_Detils.class);

        int Intfid = Integer.parseInt(fid);
        order_detils.setFid(Intfid);

        Map<Order_Detils,Integer> map=(Map<Order_Detils,Integer>)request.getSession().getAttribute("orderlist");

        Integer count = null;
        if(map==null) {
            map=new HashMap<Order_Detils,Integer>();
            request.getSession().setAttribute("orderlist", map);
            int num = order_detils.getOrderNum();
            count=num;
        }else {
            //查看该菜品是否存在
            count=map.get(order_detils.getFid());
            //如果购物车没有该菜品
            if(count==null) {
                int num = order_detils.getOrderNum();
                count=num;
            }else {
                //如果有菜品数量++
                int num = order_detils.getOrderNum();
                count=count+num;
            }
        }

        map.put(order_detils,count);
        request.setAttribute("orderlist", map);//将map传到前台


        }

   
}

此时我们已经将点单信息存入购物车中,接下来要新建购物车,查看点单信息。

(三)购物车页面的编写

SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

show.jsp:

<%@ page import="java.util.Map" %>
<%@ page import="com.RH.db.pojo.Order_Detils" %><%--
  Created by IntelliJ IDEA.
  User: RH
  Date: 2021/8/9
  Time: 21:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="layui/css/layui.css"  media="all">
    <script src="js/jquery.min.js"></script>

    <style type="text/css">
        .layui-table-cell{
            height:auto!important;
            white-space:normal;
        }

    </style>
</head>
<body>
<script src="layui/layui.js" charset="utf-8"></script>
<table align="center" class="layui-table" lay-even lay-skin="line" lay-size="lg">

    <colgroup>
        <col width="150">
        <col width="200">
        <col>
    </colgroup>
    <thead>
    <tr>
        <th>商品名称</th>
        <th>商品数量</th>
        <th>商品单价</th>
        <th>商品总价</th>
    </tr>
    </thead>
    <tbody>
    <%
        //获取购物车




        Map<Order_Detils,Integer> map= (Map<Order_Detils, Integer>) session.getAttribute("orderlist");
        //判断购物车是否为空
        if(map==null){

            out.print("<tr><td colspan='2'>未进行点单!</td></tr>");
        }else{
            //若不为空,遍历购物车

            double total=0;
            for(Order_Detils name :map.keySet()){
                total=total+name.getFoodPrice()*name.getOrderNum();
                out.print("<tr>");
                out.print("<td>");
                out.print(name.getFoodName());
                out.print("</td>");

                out.print("<td>");
                out.print(map.get(name));
                out.print("</td>");

                out.print("<td>");
                out.print(name.getFoodPrice());
                out.print("</td>");

                out.print("<td>");
                out.print(name.getFoodPrice()*name.getOrderNum());
                out.print("</td>");


            }
            out.print("</tr>");

            out.print("<tr>");

            out.print("<td>");
            out.print("</td>");

            out.print("<td>");
            out.print("</td>");

            out.print("<td>");
            out.print("</td>");

            out.print("<td>");
            out.print(total);
            out.print("</td>");

            out.print("</tr>");


        }

    %>
     </tbody>
</table>


<hr>
<center>
    <button onclick="sent()">提交订单 </button>
</center>

<script>
    function sent() {
            $.post('getorder',{},function(res){
            },"json");
        alert("提交成功!")
    }
</script>

</body>
</html>

(四)购物车功能的实现

当用户点击跳转至购物车界面,即可查看已点菜品信息,当用户单击提交时会向后台发送getorder请求。
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现
在OrderController中新增getorder()方法
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现
OrderController:

@Controller
public class OrderController {

    @Autowired
    private OrderServiceI orderServiceI;
    @Autowired
    private ResultMap resultMap;


    @RequestMapping("/orderInCart")
    public ResultMap addCartItem(String jsonStr,String fid, HttpServletRequest request) {
        try{
            orderServiceI.addCartItem(jsonStr,fid,request);
            resultMap.setStatus(true);
        }catch (Exception e){
            resultMap.setStatus(false);
            resultMap.setMessage(e.getMessage());
        }

        return resultMap;
    }

    @RequestMapping("/getorder")
    public ResultMap getorder(HttpSession session) {
        try{
            orderServiceI.getorder(session);
            resultMap.setStatus(true);
        }catch (Exception e){
            resultMap.setStatus(false);
            resultMap.setMessage(e.getMessage());
        }

        return resultMap;
    }

}

在orderServiceI、orderServiceImpl中新增getorder()方法。
orderServiceI:

public interface OrderServiceI {

    void addCartItem(String jsonStr,String fid, HttpServletRequest request) ;

	public void getorder(HttpSession session);
    
}

新建Order类:

public class Order {

    private int oid;
    private int uid;
    private String userName;
    private Double totalMoney;


    public int getOid() {
        return oid;
    }

    public void setOid(int oid) {
        this.oid = oid;
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Double getTotalMoney() {
        return totalMoney;
    }

    public void setTotalMoney(Double totalMoney) {
        this.totalMoney = totalMoney;
    }
}

orderServiceImpl:
SSM项目 蟹堡王餐厅管理系统(四)个人信息修改、点餐功能和购物车的实现

@Service
public class OrderServiceImpl implements OrderServiceI{


    @Autowired
    private OrderDao orderDao;

    @Override
    public void addCartItem(String jsonStr,String fid,HttpServletRequest request) {

        Order_Detils order_detils = JSON.parseObject(jsonStr, Order_Detils.class);

        int Intfid = Integer.parseInt(fid);
        order_detils.setFid(Intfid);

        Map<Order_Detils,Integer> map=(Map<Order_Detils,Integer>)request.getSession().getAttribute("orderlist");

        Integer count = null;
        if(map==null) {
            map=new HashMap<Order_Detils,Integer>();
            request.getSession().setAttribute("orderlist", map);
            int num = order_detils.getOrderNum();
            count=num;
        }else {
            //查看该菜品是否存在
            count=map.get(order_detils.getFid());
            //如果购物车没有该菜品
            if(count==null) {
                int num = order_detils.getOrderNum();
                count=num;
            }else {
                //如果有菜品数量++
                int num = order_detils.getOrderNum();
                count=count+num;
            }
        }

        map.put(order_detils,count);
        request.setAttribute("orderlist", map);//将map传到前台


        }

  
    @Override
    public void getorder(HttpSession session) {
        System.out.println("service");
        Map<Order_Detils,Integer> map= (Map<Order_Detils, Integer>) session.getAttribute("orderlist");

        double totalMoney=0;
        Order_Detils order_detils=new Order_Detils();
        Order order=new Order();

        int uid=0;
        String userName=null;
        for (Order_Detils data:map.keySet()) {
            uid=data.getUid();
            userName=data.getUserName();
        }


        order.setUid(uid);
        order.setUserName(userName);

        /*向数据库中插入order表,生成自增主键*/
        orderDao.insertOrder(order);

        int getoid=orderDao.selectLatestId().getOid();


        for (Order_Detils data:map.keySet()) {
            totalMoney=totalMoney+data.getFoodPrice()*data.getOrderNum();

            order_detils.setOid(getoid);
            order_detils.setFid(data.getFid());
            order_detils.setFoodName(data.getFoodName());
            order_detils.setFoodPrice(data.getFoodPrice());
            order_detils.setOrderNum(data.getOrderNum());

            /*获取订单id后,向数据库中添加订单详情*/
            int num=orderDao.insertOrderDetis(order_detils);
            if (num==0){
                throw new RuntimeException("新增订单详情失败!");
            }
        }

        order.setOid(getoid);
        order.setTotalMoney(totalMoney);

        int num=orderDao.updateOrder(order);

        ((Map<Order_Detils, Integer>) session.getAttribute("orderlist")).clear();

        if (num==0){
            throw new RuntimeException("更新订单金额失败!");
        }

    }
}

新建OrderDao,新建insertOrder()、selectLatestId()、insertOrderDetis()、updateOrder()方法

@Repository
public interface OrderDao {

    public int insertOrder(Order order);

    public Order selectLatestId();

    public int insertOrderDetis(Order_Detils order_detils);

    public int updateOrder(Order order);

}

新建ordermapper.xml:

<?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="com.RH.db.dao.OrderDao">

    <insert id="insertOrder" parameterType="com.RH.db.pojo.Order">
        insert into `order` (uid,userName) values (#{uid},#{userName});
    </insert>

    <select id="selectLatestId" resultType="com.RH.db.pojo.Order">
        select * from `order` order by oid desc limit 1;
    </select>

    <insert id="insertOrderDetis" parameterType="com.RH.db.pojo.Order_Detils">
        insert into order_detils (oid,fid,foodName,foodPrice,orderNum) values (#{oid},#{fid},#{foodName},#{foodPrice},#{orderNum});
    </insert>

    <update id="updateOrder" parameterType="com.RH.db.pojo.Order">
        update `order` set totalMoney=#{totalMoney} where oid = #{oid}
    </update>
</mapper>

至此为止个人信息修改、点餐功能和购物车已经完全实现。

上一篇:MyBatis笔记:xml映射文件


下一篇:resultMap,日志