SB_5_瑞吉外卖_4_文件上传下载_菜品新增_菜品分页查询_菜品修改

瑞吉外卖-Day04

课程内容

  • 文件上传下载
  • 菜品新增
  • 菜品分页查询
  • 菜品修改

1. 文件上传下载

1.1 上传介绍

1.1.1 概述

文件上传,也称为upload,是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。文件上传在项目中应用非常广泛,我们经常发微博、发微信朋友圈都用到了文件上传功能。

image-20210803081955246

文件上传时,对页面的form表单有如下要求:

表单属性取值说明
methodpost必须选择post方式提交
enctypemultipart/form-data采用multipart格式上传文件
typefile使用input的file控件上传
1.1.2 前端介绍

1). 简单html页面表单

<form method="post" action="/common/upload" enctype="multipart/form-data">
    <input name="myFile" type="file"  />
    <input type="submit" value="提交" /> 
</form>

2). ElementUI中提供的upload上传组件

目前一些前端组件库也提供了相应的上传组件,但是底层原理还是基于form表单的文件上传。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BcHtgxH4-1640772608564)(assets/image-20210803084742416.png)]

1.1.3 服务端介绍

服务端要接收客户端页面上传的文件,通常都会使用Apache的两个组件:

  • commons-fileupload

  • commons-io

而Spring框架在spring-web包中对文件上传进行了封装,大大简化了服务端代码,我们只需要在Controller的方法中声明一个MultipartFile类型的参数即可接收上传的文件,例如:

/**
 * 文件上传
 * @param file
 * @return
 */
@PostMapping("/upload")
public R<String> upload(MultipartFile file){
    System.out.println(file);
    return R.success(fileName);
}
1.1.4 文件上传的要求

前端代码要求:

1. 表单的请求方式必须是post请求方式,因为get请求方式有大小限制
2.  enctype=multipart/form-data  上传的文件不需要进行url的编码,使用二进制方式直接上传
3. 表单必须有一个文件上传表单项, type='file'

后端代码也是有要求:

​ 1. 对于文件上传表单项要求使用的数据类型MultipartFile

1.2 下载介绍

文件下载,也称为download,是指将文件从服务器传输到本地计算机的过程。通过浏览器进行文件下载,通常有两种表现形式:

1). 以附件形式下载,弹出保存对话框,将文件保存到指定磁盘目录

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6d8o1F1p-1640772608567)(assets/image-20210803123858691.png)]

2). 直接在浏览器中打开

而我们在今天所需要实现的菜品展示,表现形式为在浏览器中直接打开。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sac71J7Q-1640772608568)(assets/image-20210803124220869.png)]

通过浏览器进行文件下载,本质上就是服务端将文件以流的形式写回浏览器的过程。

1.3 上传代码实现

1.3.1 前端代码

文件上传,我们作为服务端工程师,主要关注服务端代码实现。对于前端页面,可以使用ElementUI提供的上传组件。可以直接使用资料中提供的上传页面,位置:资料/文件上传下载页面/upload.html,将其拷贝到项目的目录(resources/backend/page/demo)下,启动项目,访问上传页面。

http://localhost:8080/backend/page/demo/upload.html

image-20210803125619732

在上述的浏览器抓取的网络请求中,上传文件的调用url,在哪里配置的呢,这个时候,我们需要去看一下前端上传组件。

image-20210803125942295

虽然上述是ElementUI封装的代码,但是实际上最终还通过file域上传文件,如果未指定上传文件的参数名,默认为file。

image-20210803130455590
1.3.2 服务端实现

1). application.yml

需要在application.yml中定义文件存储路径

reggie:
  path: D:\img\

2). CommonController

编写文件上传的方法, 通过MultipartFile类型的参数即可接收上传的文件, 方法形参的名称需要与页面的file域的name属性一致。

所在包: com.itheima.reggie.controller

上传逻辑:

1). 获取文件的原始文件名, 通过原始文件名获取文件后缀

2). 通过UUID重新声明文件名, 文件名称重复造成文件覆盖

3). 创建文件存放目录

4). 将上传的临时文件转存到指定位置

代码实现:

package com.itheima.reggie.controller;

import com.itheima.reggie.entity.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;  //G:/img


    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //1. 获取文件名
        String originalFilename = file.getOriginalFilename();  // 1.jpg
        //2. 获取文件的拓展名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));  //.jpg
        //3. 使用UUID生成一个全新的名字
        String uuidFileName = UUID.randomUUID().toString()+ suffixName;


        //创建文件存储的目标文件夹
        File dir = new File(path);
        if(!dir.exists()){
            //如果目标目录不存在则创建
            dir.mkdirs();
        }

        //把上传文件存储到目标路径上
        File destFile = new File(dir , uuidFileName);
        file.transferTo(destFile); //把原始文件拷贝到目标位置上
        // 注意:返回的名字一定要是存储在服务器中的文件名,因为前端需要根据名字去访问图片
        return R.success(uuidFileName);
    }
}

1.3.3 测试

代码编写完成之后,我们重新启动项目,访问上传页面 http://localhost:8080/backend/page/demo/upload.html,然后点击上传图片,选择图片上传时,会发现图片并不能正常的上传,而且在浏览器中可以抓取到响应的数据,从图中我们可以判断出需要登录才可以操作。

image-20210803232054156

而这样的话,就要求我们在测试时,每一次都需要先登录,登录完成后在进行图片上传的测试,为了简化我们的测试,我们可以在 LoginCheckFilter 的doFilter方法中,在不需要处理的请求路径的数组中再加入请求路径 /common/** , 如下:

image-20210803232433983

然后,我们在测试文件的上传功能时,就不需要登录就可以操作了。

我们在测试文件上传时,可以通过debug的形式来跟踪上传的整个过程,验证一下临时文件是否存在,以及上传完成之后,临时文件是否会自动删除。

1.4 下载代码实现

1.4.1 前端代码

文件下载,前端页面可以使用标签展示下载的图片。

<img v-if="imageUrl" :src="imageUrl" class="avatar"></img>

那么,通过标签如何展示图片数据呢,接下来我们来解析一下具体的流程:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cLBNWqGK-1640772608570)(assets/image-20210803224818828.png)]

在文件上传成功后,在 handleAvatarSuccess 方法中获取文件上传成功之后返回的数据(文件名),然后调用 /common/download?name=xxx 进行文件的下载。在这里,我们想让上传的照片能够在页面展示出来,所以我们就需要在服务端将文件以流的形式写回浏览器。

1.4.2 服务端代码

在 CommonController 中定义方法download,并接收页面传递的参数name,然后读取图片文件的数据,然后以流的形式写回浏览器。

具体逻辑如下:

1). 定义输入流,通过输入流读取文件内容

2). 通过response对象,获取到输出流

3). 通过response对象设置响应数据格式(image/jpeg)

4). 通过输入流读取文件数据,然后通过上述的输出流写回浏览器

5). 关闭资源

代码实现:

 /**
     * 文件下载返回值类型void
     * @throws IOException
     */
    @GetMapping("/download")
    public void download(String name , HttpServletResponse response) throws IOException {
        //1. 找到目标文件
        File destFile = new File(path,name);
        FileInputStream fileInputStream = new FileInputStream(destFile);
        //通知浏览器当前输出的类型是图片
        response.setContentType("image/jpeg");
        //获取response的输出流,把图片的资源写出去
        ServletOutputStream outputStream = response.getOutputStream();

        //2. 边读边写
        byte[] buf =new byte[1024];
        int length =0;
        while((length = fileInputStream.read(buf))!=-1){
            outputStream.write(buf,0,length);
        }
        //3. 关闭资源
        fileInputStream.close();


    }
1.4.3 测试

访问页面 http://localhost:8080/backend/page/demo/upload.html , 点击上传图片 , 选择图片进行上传, 上传完毕之后, 查看图片是否可以展示出来。

image-20210803231134157

通过F12查询页面发起的请求及响应的数据:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yyMCoTqw-1640772608571)(assets/image-20210803231302464.png)]

2. 菜品新增

2.1 需求分析

后台系统中可以管理菜品信息,通过新增功能来添加一个新的菜品,在添加菜品时需要选择当前菜品所属的菜品分类,并且需要上传菜品图片,在移动端会按照菜品分类来展示对应的菜品信息 。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aZ3YQ3wr-1640772608573)(assets/image-20210803234122966.png)]

2.2 数据模型

image-20210803235329340

新增菜品,其实就是将新增页面录入的菜品信息插入到dish表,如果添加了口味做法,还需要向dish_flavor表插入数据。所以在新增菜品时,涉及到两个表:

表结构说明
dish菜品表
dish_flavor菜品口味表

1). 菜品表:dish

image-20210803235459347

2). 菜品口味表:dish_flavor

image-20210803235749393

2.3 准备工作

在开发业务功能前,先将需要用到的类和接口基本结构创建好:

1). 实体类 DishFlavor

直接从课程资料中导入即可,Dish实体前面课程中已经导入过了

所属包: com.itheima.reggie.entity

package com.itheima.reggie.entity;


import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
菜品口味
 */
@Data
public class DishFlavor implements Serializable {

    private static final long serialVersionUID = 1L;
	
    private Long id;
    //菜品id
    private Long dishId;

    //口味名称
    private String name;

    //口味数据list
    private String value;

    private LocalDateTime createTime;

    private LocalDateTime updateTime;

    private Long createUser;

    private Long updateUser;

    //是否删除
    private Integer isDeleted;
}

2.4 前端页面分析

基本的准备工作我们已经做完了,那么接下来我们就需要来实现新增菜品功能,在开发代码之前,需要梳理一下新增菜品时前端页面和服务端的交互过程。

1). 点击新建菜品按钮, 访问页面(backend/page/food/add.html), 页面加载时发送ajax请求,请求服务端获取菜品分类数据并展示到下拉框中

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FPOsUxcf-1640772608574)(assets/image-20210804003343531.png)]

2). 页面发送请求进行图片上传,请求服务端将图片保存到服务器(上传功能已实现)

3). 页面发送请求进行图片下载,将上传的图片进行回显(下载功能已实现)

image-20210804003752632

4). 点击保存按钮,发送ajax请求,将菜品相关数据以json形式提交到服务端

浏览器抓取请求:

image-20210804005030527

开发新增菜品功能,其实就是在服务端编写代码去处理前端页面发送的这4次请求(上传、下载已实现)即可。经过上述的分析,我们还需要在服务端实现两块功能:

A. 菜品分类数据列表查询, 具体请求信息整理如下 :

请求说明
请求方式GET
请求路径/category/list
请求参数?type=1

B. 保存菜品信息, 具体请求信息整理如下 :

请求说明
请求方式POST
请求路径/dish
请求参数json格式

下面呢,我们就需要根据这里分析的结果,分别来实现菜品分类列表的展示功能、保存菜品的功能 。

2.5 代码实现

2.5.1 菜品分类查询

在CategoryController中增加方法实现菜品分类查询,根据分类进行查询,并对查询的结果按照sort排序字段进行升序排序,如果sort相同,再按照修改时间倒序排序。

  1. CategoryController

    package com.itheima.reggie.controller;
    
    import com.itheima.reggie.common.R;
    import com.itheima.reggie.entity.Category;
    import com.itheima.reggie.entity.Page;
    import com.itheima.reggie.service.CategoryService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import java.time.LocalDateTime;
    import java.util.List;
    
    @RestController
    @RequestMapping("/category")
    public class CategoryController {
    
        @Autowired
        private CategoryService categoryService;
    
    
        
         /**
         * 作用: 根据type查询类别列表
         * @param type  类别类型
         * @return
         */
        @GetMapping("/list")
        public R<List<Category>> list(Integer type){
          R<List<Category>> result =   categoryService.list(type);
          return result;
        }
    
    
    }
    
    
  2. CategoryService

    package com.itheima.reggie.service;
    
    import com.itheima.reggie.entity.Category;
    import com.itheima.reggie.entity.Page;
    
    import java.util.List;
    
    public interface CategoryService {
    
      
    
         /**
         * 作用: 根据type查询类别列表
         * @param type  类别类型
         * @return
         */
        R<List<Category>> list(Integer type);
    }
    
    
  3. CategoryServiceImpl

    package com.itheima.reggie.service.impl;
    
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import com.itheima.reggie.entity.Category;
    import com.itheima.reggie.entity.Page;
    import com.itheima.reggie.exception.CustomException;
    import com.itheima.reggie.mapper.CategoryMapper;
    import com.itheima.reggie.mapper.DishMapper;
    import com.itheima.reggie.mapper.SetMealMapper;
    import com.itheima.reggie.service.CategoryService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class CategoryServiceImpl implements CategoryService {
    
        @Autowired(required = false)
        private CategoryMapper categoryMapper;
    
    
        @Autowired(required = false)
        private DishMapper dishMapper;
    
        @Autowired(required = false)
        private SetMealMapper setMealMapper;
    
      
    
          /**
         * 作用: 根据type查询类别列表
         * @param type  类别类型
         * @return
         */
        @Override
        public R<List<Category>> list(Integer type) {
            List<Category> categoryList = categoryMapper.list(type);
            return R.success(categoryList);
        }
    }
    
    
  4. CategoryMapper

package com.itheima.reggie.mapper;

import com.itheima.reggie.entity.Category;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.io.Serializable;
import java.util.List;

public interface CategoryMapper {

   
    List<Category> list(@Param("type") Integer type);
}

  1. CategoryMapper.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.itheima.reggie.mapper.CategoryMapper">
    
        <select id="list" resultType="category">
            select * from category
            <where>
                <if test="type!=null">
                    type=#{type}
                </if>
            </where>
        </select>
    
    </mapper>
    

代码编写完毕之后,我们可以打开新增菜品页面,查看响应的数据,及页面下拉列表的渲染情况:

image-20210804180408584
2.5.2 保存菜品信息

在上述的分析中,我们可以看到在保存菜品时,页面传递过来的是json格式数据,格式如下:

{
    "name":"佛跳墙",
    "price":88800,
    "code":"",
    "image":"da9e1c70-fc32-4781-9510-a1c4ccd2ff59.jpg",
    "description":"佛跳墙",
    "status":1,
    "categoryId":"1397844357980663809",
    "flavors":[
        {
            "name":"辣度",
            "value":"[\"不辣\",\"微辣\",\"中辣\",\"重辣\"]",
            "showOption":false
        },
        {
            "name":"忌口",
            "value":"[\"不要葱\",\"不要蒜\",\"不要香菜\",\"不要辣\"]",
            "showOption":false
        }
    ]
}

在服务端我们应该如何来封装前端传递的数据呢,我们发现,如果使用菜品类Dish来封装,只能封装菜品的基本属性,flavors属性是无法封装的。那么这个时候,我们应该如何处理呢?

这个时候,我们需要自定义一个实体类,然后继承自 Dish,并对Dish的属性进行拓展,增加 flavors 集合属性(内部封装DishFlavor)。清楚了这一点之后,接下来就进行功能开发。

1). 导入 DishDto 实体类

封装页面传递的请求参数。

所属包: com.itheima.reggie.dto

import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;

@Data
public class DishDto extends Dish {
    private List<DishFlavor> flavors = new ArrayList<>();
	
    private String categoryName;
	
    private Integer copies;
}

拓展: 我们在做项目时,经常会涉及到各种类型的实体模型。基本包含以下几种

实体模型描述
DTOData Transfer Object(数据传输对象),一般用于展示层与服务层之间的数据传输。
Entity最常用实体类,基本和数据表一一对应,一个实体类对应一张表。
VOValue Object(值对象), 主要用于封装前端页面展示的数据对象,用一个VO对象来封装整个页面展示所需要的对象数据
POPersistant Object(持久层对象), 是ORM(Objevt Relational Mapping)框架中Entity,PO属性和数据库中表的字段形成一一对应关系

2). DishController

package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;
  /**
     * 作用:保存新增菜品
     * @param dishDto  包含了菜品与口味信息
     * @param session session回话域
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody  DishDto dishDto, HttpSession session){
        //1. 获取登录用户,补全参数
        Long empId = (Long) session.getAttribute("employee");
        dishDto.setCreateUser(empId);
        dishDto.setUpdateUser(empId);
        //交给service
        dishService.save(dishDto);
        return R.success("添加菜品成功");
    }
}

3). DishService接口

package com.itheima.reggie.service;

import com.itheima.reggie.dto.DishDto;

public interface DishService {
  /**
     * 作用:保存新增菜品
     * @param dishDto  包含了菜品与口味信息
     * @return
     */
    void save(DishDto dishDto);
}

4). DishServiceImpl接口实现类

package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.dto.DishDto;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private DishFlavorMapper dishFlavorMapper;

    @Override
    public void save(DishDto dishDto) {
        //1. 补全信息
        dishDto.setCreateTime(LocalDateTime.now());
        dishDto.setUpdateTime(LocalDateTime.now());
        dishDto.setStatus(1); //正常售卖
        dishDto.setSort(0);//排序其实页面上并没有改字段,所以默认全部给0
        //2. 添加菜品
        dishMapper.save(dishDto);
        //3. 取出口味的信息,并且给每一个口味对象补全信息
        List<DishFlavor> flavorList = dishDto.getFlavors();


        //传统做法,普通遍历
       /* for (DishFlavor dishFlavor : flavorList) {
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setCreateUser(dishDto.getCreateUser());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());
        }*/

       //回顾stream流  map就是底层hi帮你遍历元素,遍历出来的每一个元素都交给你,你进行加工处理。 返回出去的元素会交给收集器collect,  返回一个集合
        //这个集合存储了加工后的元素
        flavorList = flavorList.stream().map(dishFlavor -> {
            dishFlavor.setDishId(dishDto.getId()); //补全口味所属的菜品的id
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setCreateUser(dishDto.getCreateUser());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());
            return dishFlavor;
        }).collect(Collectors.toList());

        //4. 再把口味信息插入到数据库中
        dishFlavorMapper.batchSave(flavorList);//批量插入
    }
}

5). 插入菜品,并且返回主键

package com.itheima.reggie.mapper;

import com.itheima.reggie.entity.dto.DishDto;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

public interface DishMapper {

 

    @Insert("insert into  dish values(null,#{name},#{categoryId},#{price},#{code},#{image},#{description},#{status},#{sort},#{createTime},#{updateTime},#{createUser},#{updateUser},0)")
    //插入之后主键封装给dishDto
    @Options(useGeneratedKeys = true,keyProperty = "id" , keyColumn = "id")
    void save(DishDto dishDto);
}

**6). 插入菜品口味,使用批量插入 **

package com.itheima.reggie.mapper;

import com.itheima.reggie.entity.DishFlavor;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface DishFlavorMapper {

    //批量插入口味
    void batchSave(@Param("flavorList") List<DishFlavor> flavorList);
}

<?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.itheima.reggie.mapper.DishFlavorMapper">

    <insert id="batchSave">
        insert into dish_flavor VALUES
        <foreach collection="flavorList" item="flavor" separator=",">
            (null,#{flavor.dishId},#{flavor.name},#{flavor.value},#{flavor.createTime},#{flavor.updateTime},#{flavor.createUser}
            ,#{flavor.updateUser},0)
        </foreach>
    </insert>

</mapper>

7). 在引导类上加注解 @EnableTransactionManagement

Service层方法上加的注解@Transactional要想生效,需要在引导类上加上注解 @EnableTransactionManagement, 开启对事务的支持。

@Slf4j
@SpringBootApplication
@ServletComponentScan
@EnableTransactionManagement //开启对事物管理的支持
public class ReggieApplication {
    public static void main(String[] args) {
        SpringApplication.run(ReggieApplication.class,args);
        log.info("项目启动成功...");
    }
}

2.6 功能测试

代码编写完毕之后,我们重新启动服务,访问项目,然后登陆到系统中,进行菜品的新增测试,在测试时,我们可以通过debug断点跟踪的形式,查看我们传输的数据,及数据的封装。

image-20210804174956706

debug跟踪数据的封装情况:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7uziiZXw-1640772608576)(assets/image-20210804175034622.png)]

然后在测试完毕后, 我们可以检查一下数据库中的数据保存情况:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qB0XWElw-1640772608577)(assets/image-20210804175658010.png)]

3. 菜品分页查询

3.1 需求分析

系统中的菜品数据很多的时候,如果在一个页面中全部展示出来会显得比较乱,不便于查看,所以一般的系统中都会以分页的方式来展示列表数据。

image-20210804223703893

在菜品列表展示时,除了菜品的基本信息(名称、售价、售卖状态、更新时间)外,还有两个字段略微特殊,第一个是图片字段 ,我们从数据库查询出来的仅仅是图片的名字,图片要想在表格中回显展示出来,就需要下载这个图片。第二个是菜品分类,这里展示的是分类名称,而不是分类ID,此时我们就需要根据菜品的分类ID,去分类表中查询分类信息,然后在页面展示。

3.2 前端页面分析

在开发代码之前,需要梳理一下菜品分页查询时前端页面和服务端的交互过程:

1). 访问页面(backend/page/food/list.html)时,发送ajax请求,将分页查询参数(page、pageSize、name)提交到服务端,获取分页数据

2). 页面发送请求,请求服务端进行图片下载,用于页面图片展示

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Qk81Mu2z-1640772608578)(assets/image-20210804224842336.png)]

image-20210804225259854

开发菜品信息分页查询功能,其实就是在服务端编写代码去处理前端页面发送的这2次请求即可,而前端发起的请求中, 图片文件下载回显的代码,我们已经实现了。所以,我们只需要开发分页查询的功能即可,分页查询具体的请求信息如下:

请求说明
请求方式GET
请求路径/dish/page
请求参数?page=1&pageSize=10&name=xxx

3.3 代码实现

3.3.1 分析

上述我们已经分析了分页查询的请求信息,那么接下来,我们就需要在 DishController中开发方法,来完成菜品的条件分页查询,在分页查询时还需要给页面返回分类的名称,而分类的名称前端在接收的时候是通过 categoryName 属性获取的,那么对应的服务端也应该封装到 categoryName 属性中。

<el-table-column prop="categoryName" label="菜品分类"></el-table-column>

而在我们的实体类 Dish 中,仅仅包含 categoryId, 不包含 categoryName,那么我们应该如何封装查询的数据呢? 其实,这里我们可以返回DishDto对象,在该对象中我们可以拓展一个属性 categoryName,来封装菜品分类名称。

@Data
public class DishDto extends Dish {
    private List<DishFlavor> flavors = new ArrayList<>();
    private String categoryName; //菜品分类名称
    private Integer copies;
}

具体逻辑为:

1). 构造分页条件对象

2). 构建查询及排序条件

3). 执行分页条件查询

4). 遍历分页查询列表数据,根据分类ID查询分类信息,从而获取该菜品的分类名称

5). 封装数据并返回

3.3.2 实现
  1. DishController
package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

  
  /**
     * 菜品的分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10")Integer pageSize,String name){
       R<Page<DishDto>> result =  dishService.findByPage(page,pageSize,name);
       return result;
    }
  


}    
  1. DishService
package com.itheima.reggie.service;

import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.Page;

public interface DishService {

 /**
     * 菜品的分页
     * @param page  当前页
     * @param pageSize  页面大小
     * @param name  搜索的菜品名字
     * @return
     */
    R<Page<DishDto>> findByPage(Integer page, Integer pageSize, String name);
}

  1. DishServiceImpl
package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.entity.dto.DishDto;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private DishFlavorMapper dishFlavorMapper;

    @Autowired(required = false)
    private CategoryMapper categoryMapper;

   
    /**
     * 菜品的分页
     * @param page  当前页
     * @param pageSize  页面大小
     * @param name  搜索的菜品名字
     * @return
     */
    @Override
    public R<Page<DishDto>> findByPage(Integer page, Integer pageSize, String name) {
       //1. 设置当前页与页面的大小
        PageHelper.startPage(page,pageSize);

       //2.根据名字查询菜品的列表  List<Dish>, 把List<Dish>--List<DishDto>
        List<Dish> dishList = dishMapper.findByName(name);


        //3.封装PageInfo , PageInfo<DishDto>
        PageInfo<Dish> pageInfo = new PageInfo<>(dishList);

        //把Dish转换为DishDTO
        List<DishDto> dishDtoList = pageInfo.getList().stream().map(dish -> {
            DishDto dishDto = new DishDto();
            //属性拷贝,属性拷贝的前提:属性名与属性的类型要完全一致
            BeanUtils.copyProperties(dish, dishDto);
            //根据类别的id查找类别
            Category category = categoryMapper.findbyId(dishDto.getCategoryId());
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());

        //4. 把PageInfo转换为Page对象返回.
        Page<DishDto> pageResult = new Page<>(dishDtoList,pageInfo.getTotal(),page,pageSize);
        return R.success(pageResult);
    }
}

  1. DishMapper与CategoryMapper**
package com.itheima.reggie.mapper;

import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface DishMapper {

   //根据名字查找菜品
   List<Dish> findByName(@Param("name") String name);

 
}

package com.itheima.reggie.mapper;

import com.itheima.reggie.entity.Category;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface CategoryMapper {

  

    @Select("select * from category where id=#{id}")
    Category findbyId(Long categoryId);
}

  1. DishMapper.xml
 <select id="findByName" resultType="dish">
        select * from dish
        <where>
            <if test="name!=null and name!=''">
                name like concat('%',#{name},'%')
            </if>
        </where>
    </select>

3.4 功能测试

代码编写完毕之后,我们重新启动服务,访问项目,可以通过debug端点的形式跟踪,整个分页查询过程中,数据的转换和封装。

在测试的过程中,我们发现有一些菜品图片并没有展示出来,如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WnM3X2tr-1640772608580)(assets/image-20210805100944028.png)]

这是因为我们在导入sql脚本时,导入了一部分菜品的数据,而菜品的图片在我们的磁盘目录中并不存在,所以才会出现图片展示不出来的情况,而我们后续自己添加的菜品信息是没有问题的。

4. 菜品修改

4.1 需求分析

在菜品管理列表页面点击修改按钮,跳转到修改菜品页面,在修改页面回显菜品相关信息并进行修改,最后点击确定按钮完成修改操作。

image-20210804232447587

4.2 前端页面分析

在开发代码之前,需要梳理一下修改菜品时前端页面(add.html)和服务端的交互过程:

1). 点击菜品列表的中的修改按钮,携带菜品id跳转至add.html

image-20210804233459252

2). 进入add.html,页面发送ajax请求,请求服务端获取分类数据,用于菜品分类下拉框中数据展示(已实现)

3). add.html获取id, 发送ajax请求,请求服务端,根据id查询当前菜品信息,用于菜品信息回显

image-20210804234104633

4). 页面发送请求,请求服务端进行图片下载,用于页图片回显(已实现)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9YNunvKT-1640772608581)(assets/image-20210804234226201.png)]

5). 点击保存按钮,页面发送ajax请求,将修改后的菜品相关数据以json形式提交到服务端

image-20210804234442923

经过上述的分析,我们发现,菜品分类下拉框的展示、图片的下载回显功能我们都已经实现了。我们只需要在这里实现两个功能即可,分别是:

1). 根据ID查询菜品及菜品口味信息

具体请求信息如下:

请求说明
请求方式GET
请求路径/dish/{id}

2). 修改菜品及菜品口味信息

具体请求信息如下:

请求说明
请求方式PUT
请求路径/dish
请求参数json格式数据

具体的json格式数据,我们可以通过浏览器抓取:

{
    "id":"1422783914845487106",
    "name":"佛跳墙",
    "categoryId":"1397844357980663809",
    "price":88800,
    "code":"",
    "image":"da9e1c70-fc32-4781-9510-a1c4ccd2ff59.jpg",
    "description":"佛跳墙",
    "status":1,
    "sort":0,
    "createTime":"2021-08-04 12:58:14",
    "createUser":"1412578435737350122",
    "updateUser":"1412578435737350122",
    "flavors":[
        {
            "id":"1422783914883235842",
            "dishId":"1422783914845487106",
            "name":"辣度",
            "value":"[\"不辣\",\"微辣\",\"中辣\",\"重辣\"]",
            "createTime":"2021-08-04 12:58:14",
            "updateTime":"2021-08-04 12:58:14",
            "createUser":"1412578435737350122",
            "updateUser":"1412578435737350122",
            "isDeleted":0,
            "showOption":false
        },
        {
            "id":"1422783914895818754",
            "dishId":"1422783914845487106",
            "name":"忌口",
            "value":"[\"不要葱\",\"不要蒜\",\"不要香菜\",\"不要辣\"]",
            "createTime":"2021-08-04 12:58:14",
            "updateTime":"2021-08-04 12:58:14",
            "createUser":"1412578435737350122",
            "updateUser":"1412578435737350122",
            "isDeleted":0,
            "showOption":false
        }
    ]
}

4.3 功能实现

4.3.1 根据ID查询菜品信息
4.3.1.1 代码实现

页面发送ajax请求,请求服务端,根据id查询当前菜品信息和对应的口味信息,用于修改页面中菜品信息回显。

  1. DishController根据id查找菜品
package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;


  /**
     *
     * 修改的页面信息回显
     * @param dishId
     * @return
     */
    @GetMapping("/{dishId}")
    public R<DishDto> findById(@PathVariable("dishId") Long dishId){
        R<DishDto> result = dishService.findById(dishId);
        return result;
    }

}

  1. DishService菜品
package com.itheima.reggie.service;

import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Page;

public interface DishService {

   /**
     * 根据id查找菜品
     * @param dishId
     * @return
     */
    R<DishDto> findById(Long dishId);
}

  1. DishServiceImpl菜品实现类
package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private DishFlavorMapper dishFlavorMapper;

    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    

     /**
     * 根据id查找菜品
     * @param dishId
     * @return
     */
    @Override
    public R<DishDto> findById(Long dishId) {
        //1. 根据id查找到的Dish
        Dish dish = dishMapper.findById(dishId);
        //2.把Dish转换为DishDTo,并且要往Dto设置口味信息
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        //根据菜品的id查找该菜品的口味信息
       List<DishFlavor> dishFlavorList =  dishFlavorMapper.findByDishId(dishId);
        dishDto.setFlavors(dishFlavorList);

        return R.success(dishDto);
    }
}

  1. DishMapper
package com.itheima.reggie.mapper;

import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface DishMapper {


    @Select("select * from dish where id=#{id}")
    Dish findById(Long dishId);
}

  1. DishFlavorMapper
package com.itheima.reggie.mapper;

import com.itheima.reggie.entity.DishFlavor;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface DishFlavorMapper {


    @Select("select * from dish_flavor where dish_id=#{dishId}")
    List<DishFlavor> findByDishId(Long dishId);
}

4.3.1.2 功能测试

编写完代码后,重启服务进行测试,点击列表的修改按钮,查询数据回显情况。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-C8NVIi2q-1640772608583)(assets/image-20210805101812209.png)]

4.3.2 修改菜品信息
4.3.2.1 代码实现
  1. DishController
package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

  
   
    /**
     * 作用:修改菜品
     * @param dishDto 页面传递过来的参数包含菜品与口味
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody  DishDto dishDto,HttpSession session) {
        //1. 获取当前登陆者,设置当前的修改人
        Long empId = (Long) session.getAttribute("employee");
        dishDto.setUpdateUser(empId);
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }


}    
  1. DishService 接口
package com.itheima.reggie.service;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.Page;

public interface DishService {

   
 /**
     * 作用:修改菜品
     * @param dishDto 页面传递过来的参数包含菜品与口味
     * @return
     */
    void updateWithFlavor(DishDto dishDto);
}

  1. DishServiceImpl实现类
package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;



    /**
     * 作用:修改菜品
     * @param dishDto 页面传递过来的参数包含菜品与口味
     * @return
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //1. 补全修改时间
        dishDto.setUpdateTime(LocalDateTime.now());
        //2 修改菜品
        dishMapper.updateById(dishDto);

        //3. 删除该菜品的所有口味信息
        dishFlavorMapper.deleteByDishId(dishDto.getId());

        //4. 补全口味信息,然后重新插入
        List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> dishFlavorList = flavors.stream().map((flavor -> {
            //对每一个元素进行加工
            flavor.setDishId(dishDto.getId());
            flavor.setCreateTime(LocalDateTime.now());
            flavor.setUpdateTime(LocalDateTime.now());
            flavor.setCreateUser(dishDto.getCreateUser());
            flavor.setUpdateUser(dishDto.getUpdateUser());
            return flavor;
        })).collect(Collectors.toList());

        //4. 批量保存口味信息
        dishFlavorMapper.saveBatch(dishFlavorList);

    }
}

  1. DishMapper 更新菜品
package com.itheima.reggie.mapper;

import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface DishMapper {


 

     //根据id修改菜品
    void updateById(DishDto dishDto);
}

  1. DishMapper.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">
<!-- namespace名称空间,名称空间代表该xml文件映射是哪个接口-->
<mapper namespace="com.itheima.reggie.mapper.DishMapper">
    
   

     <update id="updateById">
        update dish
        <set>
            <if test="name!=null and name!=''">
                name = #{name},
            </if>
            <if test="categoryId!=null">
                category_id = #{categoryId},
            </if>
            <if test="price!=null">
                price = #{price},
            </if>
            <if test="code!=null and code!=''">
                code = #{code},
            </if>
            <if test="image!=null and image!=''">
                image = #{image},
            </if>
            <if test="description!=null and description!=''">
                description = #{description},
            </if>
            <if test="sort!=null">
                sort = #{sort},
            </if>
            <if test="status!=null">
                status = #{status},
            </if>
            <if test="updateTime!=null">
                update_time = #{updateTime},
            </if>
            <if test="updateUser!=null">
                update_user = #{updateUser},
            </if>
        </set>
        where id=#{id}
    </update>

</mapper>
  1. DishFlavorMapper
package com.itheima.reggie.mapper;

import com.itheima.reggie.entity.DishFlavor;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface DishFlavorMapper {

   

     @Delete("delete from dish_flavor where dish_id=#{dishId}")
    void deleteByDishId(Long id);
}

.0//EN"
“http://mybatis.org/dtd/mybatis-3-mapper.dtd”>

 <update id="updateById">
    update dish
    <set>
        <if test="name!=null and name!=''">
            name = #{name},
        </if>
        <if test="categoryId!=null">
            category_id = #{categoryId},
        </if>
        <if test="price!=null">
            price = #{price},
        </if>
        <if test="code!=null and code!=''">
            code = #{code},
        </if>
        <if test="image!=null and image!=''">
            image = #{image},
        </if>
        <if test="description!=null and description!=''">
            description = #{description},
        </if>
        <if test="sort!=null">
            sort = #{sort},
        </if>
        <if test="status!=null">
            status = #{status},
        </if>
        <if test="updateTime!=null">
            update_time = #{updateTime},
        </if>
        <if test="updateUser!=null">
            update_user = #{updateUser},
        </if>
    </set>
    where id=#{id}
</update>
```
  1. DishFlavorMapper
package com.itheima.reggie.mapper;

import com.itheima.reggie.entity.DishFlavor;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface DishFlavorMapper {

   

     @Delete("delete from dish_flavor where dish_id=#{dishId}")
    void deleteByDishId(Long id);
}

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值