瑞吉外卖-Day04
课程内容
- 文件上传下载
- 菜品新增
- 菜品分页查询
- 菜品修改
1. 文件上传下载
1.1 上传介绍
1.1.1 概述
文件上传,也称为upload,是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。文件上传在项目中应用非常广泛,我们经常发微博、发微信朋友圈都用到了文件上传功能。
文件上传时,对页面的form表单有如下要求:
表单属性 | 取值 | 说明 |
---|---|---|
method | post | 必须选择post方式提交 |
enctype | multipart/form-data | 采用multipart格式上传文件 |
type | file | 使用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
在上述的浏览器抓取的网络请求中,上传文件的调用url,在哪里配置的呢,这个时候,我们需要去看一下前端上传组件。
虽然上述是ElementUI封装的代码,但是实际上最终还通过file域上传文件,如果未指定上传文件的参数名,默认为file。
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,然后点击上传图片,选择图片上传时,会发现图片并不能正常的上传,而且在浏览器中可以抓取到响应的数据,从图中我们可以判断出需要登录才可以操作。
而这样的话,就要求我们在测试时,每一次都需要先登录,登录完成后在进行图片上传的测试,为了简化我们的测试,我们可以在 LoginCheckFilter 的doFilter方法中,在不需要处理的请求路径的数组中再加入请求路径 /common/** , 如下:
然后,我们在测试文件的上传功能时,就不需要登录就可以操作了。
我们在测试文件上传时,可以通过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 , 点击上传图片 , 选择图片进行上传, 上传完毕之后, 查看图片是否可以展示出来。
通过F12查询页面发起的请求及响应的数据:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yyMCoTqw-1640772608571)(assets/image-20210803231302464.png)]
2. 菜品新增
2.1 需求分析
后台系统中可以管理菜品信息,通过新增功能来添加一个新的菜品,在添加菜品时需要选择当前菜品所属的菜品分类,并且需要上传菜品图片,在移动端会按照菜品分类来展示对应的菜品信息 。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aZ3YQ3wr-1640772608573)(assets/image-20210803234122966.png)]
2.2 数据模型
新增菜品,其实就是将新增页面录入的菜品信息插入到dish表,如果添加了口味做法,还需要向dish_flavor表插入数据。所以在新增菜品时,涉及到两个表:
表结构 | 说明 |
---|---|
dish | 菜品表 |
dish_flavor | 菜品口味表 |
1). 菜品表:dish
2). 菜品口味表:dish_flavor
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). 页面发送请求进行图片下载,将上传的图片进行回显(下载功能已实现)
4). 点击保存按钮,发送ajax请求,将菜品相关数据以json形式提交到服务端
浏览器抓取请求:
开发新增菜品功能,其实就是在服务端编写代码去处理前端页面发送的这4次请求(上传、下载已实现)即可。经过上述的分析,我们还需要在服务端实现两块功能:
A. 菜品分类数据列表查询, 具体请求信息整理如下 :
请求 | 说明 |
---|---|
请求方式 | GET |
请求路径 | /category/list |
请求参数 | ?type=1 |
B. 保存菜品信息, 具体请求信息整理如下 :
请求 | 说明 |
---|---|
请求方式 | POST |
请求路径 | /dish |
请求参数 | json格式 |
下面呢,我们就需要根据这里分析的结果,分别来实现菜品分类列表的展示功能、保存菜品的功能 。
2.5 代码实现
2.5.1 菜品分类查询
在CategoryController中增加方法实现菜品分类查询,根据分类进行查询,并对查询的结果按照sort排序字段进行升序排序,如果sort相同,再按照修改时间倒序排序。
-
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; } }
-
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); }
-
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); } }
-
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);
}
-
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>
代码编写完毕之后,我们可以打开新增菜品页面,查看响应的数据,及页面下拉列表的渲染情况:
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;
}
拓展: 我们在做项目时,经常会涉及到各种类型的实体模型。基本包含以下几种
实体模型 | 描述 |
---|---|
DTO | Data Transfer Object(数据传输对象),一般用于展示层与服务层之间的数据传输。 |
Entity | 最常用实体类,基本和数据表一一对应,一个实体类对应一张表。 |
VO | Value Object(值对象), 主要用于封装前端页面展示的数据对象,用一个VO对象来封装整个页面展示所需要的对象数据 |
PO | Persistant 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断点跟踪的形式,查看我们传输的数据,及数据的封装。
debug跟踪数据的封装情况:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7uziiZXw-1640772608576)(assets/image-20210804175034622.png)]
然后在测试完毕后, 我们可以检查一下数据库中的数据保存情况:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qB0XWElw-1640772608577)(assets/image-20210804175658010.png)]
3. 菜品分页查询
3.1 需求分析
系统中的菜品数据很多的时候,如果在一个页面中全部展示出来会显得比较乱,不便于查看,所以一般的系统中都会以分页的方式来展示列表数据。
在菜品列表展示时,除了菜品的基本信息(名称、售价、售卖状态、更新时间)外,还有两个字段略微特殊,第一个是图片字段 ,我们从数据库查询出来的仅仅是图片的名字,图片要想在表格中回显展示出来,就需要下载这个图片。第二个是菜品分类,这里展示的是分类名称,而不是分类ID,此时我们就需要根据菜品的分类ID,去分类表中查询分类信息,然后在页面展示。
3.2 前端页面分析
在开发代码之前,需要梳理一下菜品分页查询时前端页面和服务端的交互过程:
1). 访问页面(backend/page/food/list.html)时,发送ajax请求,将分页查询参数(page、pageSize、name)提交到服务端,获取分页数据
2). 页面发送请求,请求服务端进行图片下载,用于页面图片展示
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Qk81Mu2z-1640772608578)(assets/image-20210804224842336.png)]
开发菜品信息分页查询功能,其实就是在服务端编写代码去处理前端页面发送的这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 实现
- 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;
}
}
- 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);
}
- 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);
}
}
- 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);
}
- 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 需求分析
在菜品管理列表页面点击修改按钮,跳转到修改菜品页面,在修改页面回显菜品相关信息并进行修改,最后点击确定按钮完成修改操作。
4.2 前端页面分析
在开发代码之前,需要梳理一下修改菜品时前端页面(add.html)和服务端的交互过程:
1). 点击菜品列表的中的修改按钮,携带菜品id跳转至add.html
2). 进入add.html,页面发送ajax请求,请求服务端获取分类数据,用于菜品分类下拉框中数据展示(已实现)
3). add.html获取id, 发送ajax请求,请求服务端,根据id查询当前菜品信息,用于菜品信息回显
4). 页面发送请求,请求服务端进行图片下载,用于页图片回显(已实现)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9YNunvKT-1640772608581)(assets/image-20210804234226201.png)]
5). 点击保存按钮,页面发送ajax请求,将修改后的菜品相关数据以json形式提交到服务端
经过上述的分析,我们发现,菜品分类下拉框的展示、图片的下载回显功能我们都已经实现了。我们只需要在这里实现两个功能即可,分别是:
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查询当前菜品信息和对应的口味信息,用于修改页面中菜品信息回显。
- 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;
}
}
- 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);
}
- 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);
}
}
- 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);
}
- 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 代码实现
- 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("修改菜品成功");
}
}
- 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);
}
- 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);
}
}
- 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);
}
- 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>
- 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>
```
- 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);
}