目录
一、框架搭建
1、完成登录成功跳转到商品界面
2、MybatisPlusGenerator生成相关数据
3、查询分页
(1)后台制作
(2)前台编写
4、完成搜索、增加、修改、删除等功能
(1)前台编写
(2)后端编写
(3)运行测试
学习网站:layui
success(e){ // 成功的回调函数 layer.alert(e.message, {icon: 6}, () => { if (e.code === 200) { location.href = "/goods/goodsList" } }); },
①、增加PageBean帮助类
package com.mwy.seckill.util;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageBean {
private int total;
private int page = 1;
private int rows = 5;
private boolean pagination = true;
private String url;
private Map ms;
public void setMs(Map ms) {
this.ms = ms;
}
public int calcStartIndex() {
return (page - 1) * rows;
}
public int calcMaxPage() {
return total % rows == 0 ? total / rows : total / rows + 1;
}
public int nextPage() {
return Math.min(page + 1, calcMaxPage());
}
public int prevPage() {
return Math.max(page - 1, 1);
}
public void setRequest(HttpServletRequest req) {
setUrl(req.getRequestURL().toString());
setMs(req.getParameterMap());
String page = req.getParameter("page");
if (page == null) {
setPage(1);
} else {
setPage(Integer.parseInt(page));
}
String rows = req.getParameter("rows");
if (rows == null) {
setRows(5);
} else {
setRows(Integer.parseInt(rows));
}
String pagination = req.getParameter("pagination");
if ("false".equals(pagination)) {
setPagination(false);
}
}
}
②、接口:IGoodsService
package com.mwy.seckill.service;
import com.mwy.seckill.pojo.Goods;
import com.baomidou.mybatisplus.extension.service.IService;
import com.mwy.seckill.util.PageBean;
import com.mwy.seckill.util.response.ResponseResult;
import java.util.List;
/**
*
* 商品信息表 服务类
*
*
* @author mwy
* @since 2022-03-19
*/
public interface IGoodsService extends IService {
ResponseResult> queryGoodsListByPage(Goods goods, PageBean pageBean);
}
③、实现接口:GoodsServiceImpl
package com.mwy.seckill.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.mwy.seckill.pojo.Goods;
import com.mwy.seckill.mapper.GoodsMapper;
import com.mwy.seckill.service.IGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mwy.seckill.util.PageBean;
import com.mwy.seckill.util.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
*
* 商品信息表 服务实现类
*
*
* @author mwy
* @since 2022-03-19
*/
@Service
public class GoodsServiceImpl extends ServiceImpl implements IGoodsService {
@Autowired
private GoodsMapper goodsMapper;
@Override
public ResponseResult> queryGoodsListByPage(Goods goods, PageBean pageBean) {
// 分页
Page page = PageDTO.of(pageBean.getPage(), pageBean.getRows());
// 模糊条件+条件
QueryWrapper wrapper = new QueryWrapper();
if (StringUtils.isNotEmpty(goods.getGoodsName())) {
wrapper.like("goods_name", "%" + goods.getGoodsName() + "%");
}
// 数据查询结果
Page result = goodsMapper.selectPage(page, wrapper);
return ResponseResult.success(result.getRecords(), result.getTotal());
}
}
插件实现分页,增加MybatisPlusConfig(mybatis plus官方文档中插件主体spring-boot
路径:插件主体)不增加插件,page没有用,还会查询保错。
package com.mwy.seckill.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
④、GoodsMapper增加注解
⑤、GoodsController
package com.mwy.seckill.controller;
import com.mwy.seckill.pojo.Goods;
import com.mwy.seckill.service.IGoodsService;
import com.mwy.seckill.util.PageBean;
import com.mwy.seckill.util.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
*
* 商品信息表 前端控制器
*
*
* @author mwy
* @since 2022-03-19
*/
@RestController
@RequestMapping("/goods")
public class GoodsController {
@Autowired
private IGoodsService goodsService;
@RequestMapping("/queryAll")
public ResponseResult> queryGoodsListByPage(Goods goods, HttpServletRequest request) {
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
return goodsService.queryGoodsListByPage(goods, pageBean);
}
}
查询数据成功:
①、页面编写
goodsList.ftl:
<#include "../common/head.ftl">
- 普通商品
- 秒杀商品
内容2
②、js代码编写
goodsList.js:
layui.define(() => {
let table = layui.table;
let layer = layui.layer
let normal = table.render({
elem: '#normal_goods',
height: 550,
url: '/goods/queryAll', //数据接口
page: true,//开启分页
parseData(res) { //res 即为原始返回的数据
return {
"code": res.code === 200 ? 0 : 1, //解析接口状态
"msg": res.message, //解析提示文本
"count": res.total, //解析数据长度
"data": res.data //解析数据列表
}
},
cols: [[ //表头
{field: 'gid', title: '商品编号', width: 100, sort: true, fixed: 'left'},
{field: 'goodsName', title: '商品名称'},
{field: 'goodsTitle', title: '商品标题'},
{
field: 'goodsImg',
title: '商品图片',
width: 200,
templet: (goods) => "" + goods.goodsImg + ""
},
{field: 'goodsDetail', title: '商品签名'},
{field: 'goodsPrice', title: '商品价格', sort: true},
{field: 'goodsStock', title: '商品库存', sort: true},
]]
});
})
let showImg = (src, obj) => {
layer.tips(``, obj);
}
③、页面展示
①、goodsList.ftl:
<#include "../common/head.ftl">
- 普通商品
- 秒杀商品
<#--搜索、新增-->
<#--表格-->
<#--相关操作按钮 ,工具条模板-->
内容2
②、goodsList.js
/*子界面的数据*/
var row
layui.define(() => {
let table = layui.table;
//定义jQuery
let $ = layui.jquery;
let layer = layui.layer
let normal = table.render({
elem: '#normal_goods',
height: 550,
url: '/goods/queryAll', //数据接口
page: true,//开启分页
parseData(res) { //res 即为原始返回的数据
return {
"code": res.code === 200 ? 0 : 1, //解析接口状态
"msg": res.message, //解析提示文本
"count": res.total, //解析数据长度
"data": res.data //解析数据列表
}
},
/*异步数据*/
request: {
pageName: 'page', //页码的参数名称,默认:page
limitName: 'rows' //每页数据量的参数名,默认:limit
},
/*表格*/
cols: [[ //表头
{field: 'gid', title: '商品编号', width: 100, sort: true, fixed: 'left'},
{field: 'goodsName', title: '商品名称'},
{field: 'goodsTitle', title: '商品标题'},
{
field: 'goodsImg',
title: '商品图片',
width: 200,
templet: (goods) => "" + goods.goodsImg + ""
},
{field: 'goodsDetail', title: '商品签名'},
{field: 'goodsPrice', title: '商品价格', sort: true},
{field: 'goodsStock', title: '商品库存', sort: true},
/* toolbar:绑定工具条模板 */
{field: 'operate', title: '操作', toolbar: "#button_1"}
]]
});
/* 刷新数据 */
let reload = () => {
let goodsName = $("#normal_value").val()
normal.reload({
where: {
//设定异步数据接口的额外参数
goodsName
},
page: {
curr: 1// current
}
})
}
/* 搜索 */
$("#normal_search").click(() => {
reload()
})
/* 增加 */
$("#normal_add").click(() => {
row = null//增加不用获取行数,直接增加
openDialogs()//弹出页面增加数据
})
/* 工具条事件,绑定在normal_goods表格上的工具条 */
table.on("tool(normal_goods)", obj => {
let data = obj.data; //获得当前行数据
let layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
let tr = obj.tr; //获得当前行 tr 的 DOM 对象(如果有的话)
console.log(obj)
if (layEvent === 'normal_del') {// 删除
row = data//获得当前行的数据
let url="/goods/del/"+data.gid
layer.confirm('确定删除吗?',{title:'删除'}, function(index){
//向服务端发送删除指令og
$.getJSON(url,{gid:data.gid}, function(ret){
layer.close(index);//关闭弹窗
reload()
});
layer.close(index);//关闭弹窗
});
}
if (layEvent === 'normal_edit') {//编辑,修改
row = data//获得当前行的数据
openDialogs()//打开弹框
}
})
/* 弹出层,页面层 */
let openDialogs = () => {
layer.open({
type: 2,
content: "/goods/goodsOperate",//路径
area: ['900px', '600px'],//设置宽高
btn: ['确定', '取消'],//弹出层按钮
yes(index, layero) {//回调函数 index是“确定”的回调函数,layero是子界面“goodsOperate.ftl”
//增加
let url = "/goods/insert"
if (row) {
//编辑,修改
url = "/goods/edit"
}
//拿到当前子界面(goodsOperate.ftl)js(goodsOperate.js)的window对象(loadFormData)调用getFormData方法
//iframe:可以有多个
let data = $(layero).find("iframe")[0].contentWindow.getFormData()
//ajax访问
$.ajax({
url,//填写路径
dataType: "json",//返回类型
data,//发送给后台的数据
async: false,
//回调函数
success(res) {
layer.closeAll()//关闭所有
reload()//刷新数据
layer.msg(res.message)
}
})
}
})
}
})
/* 图片查看 */
let showImg = (src, obj) => {
layer.tips(``, obj);
}
③、弹出框
Ⅰ、弹出框界面(goodsOperate.ftl)
Ⅱ、弹出框js(goodsOperate.js)
let form, $
/* 拿到form表单、jQuery */
layui.define(() => {
form = layui.form
$ = layui.jquery
loadFormData()
})
/* 子界面引用父界面使用parent */
function loadFormData() {
if (parent.row) {
form.val('goods_operate', $.extend({}, parent.row || {}));
}
}
/*
将表单的对象转成一个值,丢出去
父界面想使用子界面直接调用getFormData方法即可
*/
function getFormData() {
return form.val("goods_operate")
}
①、service层
Ⅰ、IGoodsService (接口)
package com.mwy.seckill.service;
import com.mwy.seckill.pojo.Goods;
import com.baomidou.mybatisplus.extension.service.IService;
import com.mwy.seckill.util.PageBean;
import com.mwy.seckill.util.response.ResponseResult;
import java.util.List;
/**
*
* 商品信息表 服务类
*
*
* @author mwy
* @since 2022-03-19
*/
public interface IGoodsService extends IService {
// 查询分页
ResponseResult> queryGoodsListByPage(Goods goods, PageBean pageBean);
// 删除
ResponseResult> deleteGoodsById(Long goodsId);
// 修改
ResponseResult> editGoodsById(Goods goods);
// 增加
ResponseResult> insertGoods(Goods goods);
}
Ⅱ、实现接口GoodsServiceImpl
package com.mwy.seckill.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.mwy.seckill.pojo.Goods;
import com.mwy.seckill.mapper.GoodsMapper;
import com.mwy.seckill.service.IGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mwy.seckill.util.PageBean;
import com.mwy.seckill.util.response.ResponseResult;
import com.mwy.seckill.util.response.ResponseResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
*
* 商品信息表 服务实现类
*
*
* @author mwy
* @since 2022-03-19
*/
@Service
public class GoodsServiceImpl extends ServiceImpl implements IGoodsService {
@Autowired
private GoodsMapper goodsMapper;
// 查询分页
@Override
public ResponseResult> queryGoodsListByPage(Goods goods, PageBean pageBean) {
// 分页
Page page = PageDTO.of(pageBean.getPage(), pageBean.getRows());
// 模糊条件+条件
QueryWrapper wrapper = new QueryWrapper();
if (StringUtils.isNotEmpty(goods.getGoodsName())) {
wrapper.like("goods_name", "%" + goods.getGoodsName() + "%");
}
// 数据查询结果
Page result = goodsMapper.selectPage(page, wrapper);
return ResponseResult.success(result.getRecords(), result.getTotal());
}
// 删除
@Override
public ResponseResult> deleteGoodsById(Long goodsId) {
boolean b = this.removeById(goodsId);
if (b) {
return ResponseResult.success();
}
return ResponseResult.failure(ResponseResultCode.UNKNOWN);
}
// 修改
@Override
public ResponseResult> editGoodsById(Goods goods) {
boolean b = this.updateById(goods);
if (b) {
return ResponseResult.success();
}
return ResponseResult.failure(ResponseResultCode.UNKNOWN);
}
// 增加
@Override
public ResponseResult> insertGoods(Goods goods) {
boolean b = this.save(goods);
if (b) {
return ResponseResult.success();
}
return ResponseResult.failure(ResponseResultCode.UNKNOWN);
}
}
②、GoodsController
package com.mwy.seckill.controller;
import com.mwy.seckill.pojo.Goods;
import com.mwy.seckill.service.IGoodsService;
import com.mwy.seckill.util.PageBean;
import com.mwy.seckill.util.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
*
* 商品信息表 前端控制器
*
*
* @author mwy
* @since 2022-03-19
*/
@RestController
@RequestMapping("/goods")
public class GoodsController {
@Autowired
private IGoodsService goodsService;
@RequestMapping("/queryAll")
public ResponseResult> queryGoodsListByPage(Goods goods, HttpServletRequest request) {
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
return goodsService.queryGoodsListByPage(goods, pageBean);
}
@RequestMapping("/del/{gid}")
public ResponseResult> deleteGoodsById(@PathVariable("gid") Long gid) {
return goodsService.deleteGoodsById(gid);
}
@RequestMapping("/edit")
public ResponseResult> editGoodsById(Goods goods) {
return goodsService.editGoodsById(goods);
}
@RequestMapping("/insert")
public ResponseResult> insertGoods(Goods goods) {
return goodsService.insertGoods(goods);
}
}
①、新增
②、编辑商品
③、查询
④、删除
结束!!!!