店铺编辑
Dao层开发
- ShopDao接口
package com.imooc.o2o.dao;
import com.imooc.o2o.entity.Shop;
public interface ShopDao {
// 新增店铺 返回1成功 返回-1失败
int insertShop(Shop shop);
// 更新店铺信息
int updateShop(Shop shop);
// 通过shop id 查询店铺
Shop queryByShopId(long shopid);
}
- 在shopDao.xml中添加shopMap文件
<mapper namespace="com.imooc.o2o.dao.ShopDao">
<resultMap id="shopMap" type="com.imooc.o2o.entity.Shop">
<id column="shop_id" property="shopId"/>
<result column="shop_name" property="shopName"/>
<result column="shop_desc" property="shopDesc" />
<result column="shop_addr" property="shopAddr" />
<result column="phone" property="phone" />
<result column="shop_img" property="shopImg" />
<result column="longitude" property="longitude" />
<result column="latitude" property="latitude" />
<result column="priority" property="priority" />
<result column="create_time" property="createTime" />
<result column="last_edit_time" property="lastEditTime" />
<result column="enable_status" property="enableStatus" />
<result column="advice" property="advice" />
<association property="area" column="area_id" javaType="com.imooc.o2o.entity.Area">
<id column="area_id" property="areaId"/>
<result column="area_name" property="areaName"/>
</association>
<association property="shopCategory" column="shop_category_id" javaType="com.imooc.o2o.entity.ShopCategory">
<id column="shop_category_id" property="shopCategoryId"/>
<result column="shop_category_name" property="shopCategoryName"/>
</association>
<association property="owner" column="user_id" javaType="com.imooc.o2o.entity.PersonInfo">
<id column="user_id" property="userId"/>
<result column="name" property="name"/>
</association>
</resultMap>
- 在shopDao.xml 中添加
<select id="queryByShopId" resultMap="shopMap" parameterType="Long">
SELECT
s.shop_id,
s.shop_name,
s.shop_desc,
s.phone,
s.shop_img,
s.priority,
s.create_time,
s.last_edit_time,
s.enable_status,
s.advice,
a.area_id,
a.area_name,
sc.shop_category_id,
sc.shop_category_name
FROM
tb_shop s,
tb_area a,
tb_shop_category sc
WHERE
s.area_id = a.area_id
AND
s.shop_category_id = sc.shop_category_id
AND
s.shop_id = #{shopId}
</select>
- 测试
@Test
public void testQueryByShopId() {
long shopId = 5L;
Shop shop = shopDao.queryByShopId(shopId);
System.out.println("areaId:" + shop.getArea().getAreaId());
System.out.println("areaName:" + shop.getArea().getAreaName());
}
-
测试结果
image.png
Service层实现
- 在ImageUtil中添加deleteFileOrPath的方法
/**
* storePath 是文件的路径还是目录的路径
* 如果storePath是文件的路径则删除该文件
* 如果storePath是目录的路径则删除工目录下的所有文件
* @param storePath
*/
public static void deleteFileOrPath(String storePath) {
File fileOrPath = new File(PathUtil.getImgBasePath() + storePath);
if (fileOrPath.exists()) {
// 如果是目录
if (fileOrPath.isDirectory()) {
File file[] = fileOrPath.listFiles();
for (int i = 0; i < file.length; i++) {
file[i].delete();
}
}
// 如果是文件
fileOrPath.delete();
}
}
- 在ShopServiceImpl中
@Override
public ShopExecution modifyShop(Shop shop, InputStream shopImgInputStrem, String fileName) throws ShopOperationException {
if (shop == null || shop.getShopId() == null) {
return new ShopExecution(ShopStateEnum.NULL_SHOP);
}
try {
// 1.判断是否需要处理图片
if (shopImgInputStrem != null && fileName != null && !"".equals(fileName)) {
Shop tempShop = shopDao.queryByShopId(shop.getShopId());
// 之前的图片存在
if (tempShop.getShopImg() != null) {
ImageUtil.deleteFileOrPath(tempShop.getShopImg());
}
addShopImg(shop, shopImgInputStrem, fileName);
}
// 2.更新店铺信息
shop.setLastEditTime(new Date());
int effectNum = shopDao.updateShop(shop);
if (effectNum <= 0) {
return new ShopExecution(ShopStateEnum.INNER_ERROR);
} else {
shop = shopDao.queryByShopId(shop.getShopId());
return new ShopExecution(ShopStateEnum.SUCCESS, shop);
}
} catch (Exception e) {
throw new ShopOperationException("modifyShop error" + e.getMessage());
}
}
- 测试
@Test
public void testModifyShop() throws ShopOperationException, FileNotFoundException {
Shop shop = new Shop();
shop.setShopId(23L);
shop.setShopName("修改后的店铺名称");
File shopImg = new File("D:\\123.jpg");
InputStream inputStream = new FileInputStream(shopImg);
ShopExecution shopExecution = shopService.modifyShop(shop, inputStream, "123.jpg");
System.out.println("新的图片地址:" + shopExecution.getShop().getShopImg());
}
-
测试结果
image.png
Controller层实现
- ShopManageController中
@RequestMapping(value = "/getshopbyid", method = RequestMethod.GET)
@ResponseBody
private Map<String, Object> getShopById(HttpServletRequest request) {
Map<String, Object> modelMap = new HashMap<>();
Long shopId = HttpServletRequestUtil.getLong(request, "shopid");
if (shopId > -1) {
try {
Shop shop = shopService.getByShopId(shopId);
List<Area> areaList = areaService.getAreaList();
modelMap.put("shop", shop);
modelMap.put("areaList", areaList);
modelMap.put("success", true);
} catch (Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
}
} else {
modelMap.put("success", false);
modelMap.put("errMsg", "empty shopId");
}
return modelMap;
}
-
测试结果
image.png
- 商店编辑Controller
@RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
@ResponseBody
private Map<String, Object> modifyShop(HttpServletRequest request) {
Map<String, Object> modelMap = new HashMap<>();
// 1. 接受并转化相应的参数 包括店铺信息以及图片信息
String shopstr = HttpServletRequestUtil.getString(request, "shopStr");
ObjectMapper mapper = new ObjectMapper();
Shop shop = null;
try{
shop = mapper.readValue(shopstr, Shop.class);
} catch (Exception E) {
modelMap.put("success", false);
modelMap.put("errMsg", E.getMessage());
return modelMap;
}
CommonsMultipartFile shopImg = null;
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
if (commonsMultipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
}
// 2. 修改店铺信息
if (shop != null && shop.getShopImg() != null) {
PersonInfo owner = new PersonInfo();
owner.setUserId(1L);
shop.setOwner(owner);
ShopExecution shopExecution = null;
try {
if (shopImg == null) {
shopExecution = shopService.modifyShop(shop, null, null);
} else {
shopExecution = shopService.modifyShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
}
} catch (IOException e) {
e.printStackTrace();
}
if (shopExecution.getState() == ShopStateEnum.SUCCESS.getState()) {
modelMap.put("success", true);
} else {
modelMap.put("success", false);
modelMap.put("errMsg", shopExecution.getStateInfo());
}
return modelMap;
} else {
modelMap.put("success", false);
modelMap.put("errMsh", "请输入店铺id");
return modelMap;
}
}
- 修改js文件
$(function() {
// var shopId = getQueryString('shopId');
var shopId = 23;
var isEdit = shopId ? true : false;
// var shopInfoUrl = '/project2/shop/getshopbyid?shopId=23';
var shopInfoUrl = '/project2/shop/getshopbyid?shopId=' + shopId;
var initUrl = '/project2/shop/getshopinitinfo';
var editShopUrl = '/project2/shop/registershop';
if (isEdit) {
editShopUrl = '/project2/shop/modifyshop';
}
function getInfo(shopId) {
$.getJSON(shopInfoUrl, function(data) {
if (data.success) {
var shop = data.shop;
$('#shop-name').val(shop.shopName);
$('#shop-addr').val(shop.shopAddr);
$('#shop-phone').val(shop.phone);
$('#shop-desc').val(shop.shopDesc);
var shopCategory = '<option data-id="'
+ shop.shopCategory.shopCategoryId + '" selected>'
+ shop.shopCategory.shopCategoryName + '</option>';
var tempAreaHtml = '';
data.areaList.map(function(item, index) {
tempAreaHtml += '<option data-id="' + item.areaId + '">'
+ item.areaName + '</option>';
});
$('#shop-category').html(shopCategory);
$('#shop-category').attr('disabled','disabled');
$('#area').html(tempAreaHtml);
$('#area').attr('data-id',shop.areaId);
}
});
}
function getCategory() {
$.getJSON(initUrl, function(data) {
if (data.success) {
var tempHtml = '';
var tempAreaHtml = '';
data.shopCategoryList.map(function(item, index) {
tempHtml += '<option data-id="' + item.shopCategoryId
+ '">' + item.shopCategoryName + '</option>';
});
data.areaList.map(function(item, index) {
tempAreaHtml += '<option data-id="' + item.areaId + '">'
+ item.areaName + '</option>';
});
$('#shop-category').html(tempHtml);
$('#shop-category').removeAttr('disabled');
$('#area').html(tempAreaHtml);
}
});
}
if (isEdit) {
getInfo(shopId);
} else {
getCategory();
}
$('#submit').click(function() {
var shop = {};
if (isEdit) {
shop.shopId = shopId;
}
shop.shopName = $('#shop-name').val();
shop.shopAddr = $('#shop-addr').val();
shop.phone = $('#shop-phone').val();
shop.shopDesc = $('#shop-desc').val();
shop.shopCategory = {
shopCategoryId : $('#shop-category').find('option').not(function() {
return !this.selected;
}).data('id')
};
shop.area = {
areaId : $('#area').find('option').not(function() {
return !this.selected;
}).data('id')
};
var shopImg = $("#shop-img")[0].files[0];
var formData = new FormData();
formData.append('shopImg', shopImg);
formData.append('shopStr', JSON.stringify(shop));
var verifyCodeActual = $('#j_captcha').val();
if (!verifyCodeActual) {
$.toast('请输入验证码!');
return;
}
formData.append("verifyCodeActual", verifyCodeActual);
$.ajax({
url : editShopUrl,
type : 'POST',
// contentType: "application/x-www-form-urlencoded; charset=utf-8",
data : formData,
contentType : false,
processData : false,
cache : false,
success : function(data) {
if (data.success) {
$.toast('提交成功!');
if (isEdit){
$('#captcha_img').click();
} else{
window.location.href="/shop/shoplist";
}
} else {
$.toast('提交失败!');
$('#captcha_img').click();
}
}
});
});
});
-
测试
image.png
-
测试结果
image.png
列表功能
Dao层的实现
- 接口
因为多个参数,所以@Param作为唯一的标识
/**
* 分页查询 可输入的条件有:店铺名(模糊). 店铺状态 区域id owner
* @param shopCondition 查询的条件
* @param rowIndex 从第几行开始取数据
* @param pageSize 返回的条数
* @param
* @return
*/
List<Shop> queryShopList(@Param("shopCondition") Shop shopCondition,
@Param("rowIndex") int rowIndex,
@Param("pageSize") int pageSize);
/**
* 查询总数
* @param shopCondition
* @return
*/
int queryShopCount(@Param("shopCondition") Shop shopCondition);
- Mapper中
<select id="queryShopList" resultMap="shopMap">
SELECT
s.shop_id,
s.shop_name,
s.shop_desc,
s.phone,
s.shop_img,
s.priority,
s.create_time,
s.last_edit_time,
s.enable_status,
s.advice,
a.area_id,
a.area_name,
sc.shop_category_id,
sc.shop_category_name
FROM
tb_shop s,
tb_area a,
tb_shop_category sc
<where>
<if test="shopCondition.shopCategory != null and shopCondition.shopCategory.shopCategoryId != null">
AND s.shop_category_id = #{shopCondition.shopCategoryId}
</if>
<if test="shopCondition.area != null and shopCondition.area.areaId != null">
AND s.shop_area_id = #{shopCondition.areaId}
</if>
<if test="shopCondition.shopName != null">
AND s.shop_name LIKE "%${shopCondition.shopName}%"
</if>
<if test="shopCondition.enableStatus != null">
AND s.enable_status = #{shopCondition.enableStatus}
</if>
<if test="shopCondition.owner != null and shopCondition.owner.userId != null">
AND s.owner_id = #{shopCondition.owner.userId}
</if>
AND
s.area_id = a.area_id
AND
s.shop_category_id = sc.shop_category_id
</where>
ORDER BY
s.priority DESC
LIMIT #{rowIndex}, #{pageSize}
</select>
<select id="queryShopCount" resultType="int">
SELECT
count(1)
FROM
tb_shop s,
tb_area a,
tb_shop_category sc
<where>
<if test="shopCondition.shopCategory != null and shopCondition.shopCategory.shopCategoryId != null">
AND s.shop_category_id = #{shopCondition.shopCategoryId}
</if>
<if test="shopCondition.area != null and shopCondition.area.areaId != null">
AND s.shop_area_id = #{shopCondition.areaId}
</if>
<if test="shopCondition.shopName != null">
AND s.shop_name LIKE "%${shopCondition.shopName}%"
</if>
<if test="shopCondition.enableStatus != null">
AND s.enable_status = #{shopCondition.enableStatus}
</if>
<if test="shopCondition.owner != null and shopCondition.owner.userId != null">
AND s.owner_id = #{shopCondition.owner.userId}
</if>
</where>
AND
s.area_id = a.area_id
AND
s.shop_category_id = sc.shop_category_id
</select>
- 测试
@Test
public void testQueryShopList() {
Shop shopCondition = new Shop();
PersonInfo owner = new PersonInfo();
owner.setUserId(1L);
shopCondition.setOwner(owner);
List<Shop> list =shopDao.queryShopList(shopCondition, 0, 5);
System.out.println(list.size());
}
@Test
public void testQueryShopCount() {
Shop shopCondition = new Shop();
PersonInfo owner = new PersonInfo();
owner.setUserId(1L);
shopCondition.setOwner(owner);
int count =shopDao.queryShopCount(shopCondition);
System.out.println(count);
}
-
测试结果
image.png
报错,改为如下
<if test="shopCondition.shopCategory != null and shopCondition.shopCategory.shopCategoryId != null">
AND s.shop_category_id = #{shopCondition.shopCategory.shopCategoryId}


Service层的实现
- 接口
/**
* 根据shopCondition分页返回相应的店铺列表
* @param shopCondition
* @param pageIndex
* @param pageSize
* @return
*/
ShopExecution getShopList(Shop shopCondition, int pageIndex, int pageSize);
- 编写一个工具类
package com.imooc.o2o.util;
public class PageCalculator {
/**
* 比如 页码 1 大小 5 则 第1页的第一个条数据为 0
* 页码 2 大小 5 则 第2页的第一条数据类 5
* @param pageIndex
* @param pageSize
* @return
*/
public static int calculateRowIndex(int pageIndex, int pageSize) {
return (pageIndex > 0) ? (pageIndex - 1) * pageSize : 0;
}
}
- 实现类
@Override
public ShopExecution getShopList(Shop shopCondition, int pageIndex, int pageSize) {
int rowIndex = PageCalculator.calculateRowIndex(pageIndex, pageSize);
List<Shop> shopList = shopDao.queryShopList(shopCondition, rowIndex, pageSize);
int count = shopDao.queryShopCount(shopCondition);
ShopExecution shopExecution = new ShopExecution();
if (shopList != null) {
shopExecution.setShopList(shopList);
shopExecution.setCount(count);
} else {
shopExecution.setState(ShopStateEnum.INNER_ERROR.getState());
}
return shopExecution;
}
- 测试
@Test
public void testGetShopList() {
Shop shopCondition = new Shop();
ShopCategory shopCategory = new ShopCategory();
shopCategory.setShopCategoryId(1L);
shopCondition.setShopCategory(shopCategory);
ShopExecution shopExecution = shopService.getShopList(shopCondition, 1, 5);
System.out.println("店铺列表数" + shopExecution.getShopList().size());
System.out.println("店铺总数" + shopExecution.getCount());
}
-
测试结果
image.png
Controller层的实现
- 添加一个getShopList的方法
@RequestMapping(value = "/getshoplist", method = RequestMethod.GET)
@ResponseBody
private Map<String, Object> getShopList(HttpServletRequest request) {
Map<String, Object> modelMap = new HashMap<>();
PersonInfo user = new PersonInfo();
user.setUserId(1L);
user.setName("cuzz");
request.getSession().setAttribute("user", user);
user = (PersonInfo) request.getSession().getAttribute("user");
try {
Shop shopCondition = new Shop();
shopCondition.setOwner(user);
ShopExecution se = shopService.getShopList(shopCondition, 0, 100);
modelMap.put("shopList", se.getShopList());
modelMap.put("user", user);
modelMap.put("success", true);
} catch (Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
}
return modelMap;
}
- js代码
$(function () {
function getlist(e) {
$.ajax({
url : "/project2/shop/getshoplist",
type : "get",
dataType : "json",
success : function(data) {
if (data.success) {
handleList(data.shopList);
handleUser(data.user);
}
}
});
}
function handleUser(data) {
$('#user-name').text(data.name);
}
function handleList(data) {
var html = '';
data.map(function (item, index) {
html += '<div class="row row-shop"><div class="col-40">'+ item.shopName +'</div><div class="col-40">'+ shopStatus(item.enableStatus) +'</div><div class="col-20">'+ goShop(item.enableStatus, item.shopId) +'</div></div>';
});
$('.shop-wrap').html(html);
}
function goShop(status, id) {
if (status != 0 && status != -1) {
return '<a href="/project2/shop/shopmanage?shopId='+ id +'">进入</a>';
} else {
return '';
}
}
function shopStatus(status) {
if (status == 0) {
return '审核中';
} else if (status == -1) {
return '店铺非法';
} else {
return '审核通过';
}
}
$('#log-out').click(function () {
$.ajax({
url : "/project2/shop/logout",
type : "post",
contentType : false,
processData : false,
cache : false,
success : function(data) {
if (data.success) {
window.location.href = '/project2/shop/ownerlogin';
}
},
error : function(data, error) {
alert(error);
}
});
});
getlist();
});
-
测试
image.png
- 返回页面
package com.imooc.o2o.web.shopadmin;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(value = "shopadmin", method = RequestMethod.GET)
public class ShopAdminController {
@RequestMapping(value="/shopoperation")
public String shopOperation() {
return "shop/shopedit";
}
@RequestMapping(value="/shoplist")
public String shoplist() {
return "shop/shoplist";
}
}
- 测试
http://localhost:8080/project2/shopadmin/shoplist
image.png
管理页面
- 返回页面
@RequestMapping(value="/shopmanagement")
public String shopManagement() {
return "shop/shopmanagement";
}
- js代码
$(function () {
var shopId = getQueryString("shopId");
alert(shopId);
var shopInfoUrl = "/project2/shop/getshopmanagementinfo?shopId=" + shopId;
alert("测试shopmanage");
// 记得回调函数里有data
$.getJSON(shopInfoUrl, function (data) {
if (data.redirect) {
window.location.href = data.url;
} else {
if (data.shopId != undefined && data.shopId != null) {
shopId = data.shopId;
}
}
$("#shopInfo").attr("href", "/project2/shopadmin/shopedit?shopId=" + shopId);
});
});
- 获取店铺信息
@RequestMapping(value = "/getshopmanagementinfo", method = RequestMethod.GET)
@ResponseBody
private Map<String, Object> getShopManagementInfo(HttpServletRequest request) {
Map<String, Object> modelMap = new HashMap<>();
long shopId = HttpServletRequestUtil.getLong(request, "shopId");
// 如果前端没有传shopId来
if (shopId <= 0) {
Object currentShopObj = request.getSession().getAttribute("currentShop");
// 如果还是没有获取shop
if (currentShopObj == null) {
// 重定向
modelMap.put("redirect", true);
modelMap.put("url","/project2/shop/shoplist");
} else {
Shop currentShop = (Shop) currentShopObj;
modelMap.put("redirect", false);
modelMap.put("shopId", currentShop.getShopId());
}
} else {
Shop currentShop = new Shop();
currentShop.setShopId(shopId);
request.getSession().setAttribute("currentShop", currentShop);
modelMap.put("redirect", false);
}
return modelMap;
}
-
测试
image.png
image.png
image.png
也能进入到页面的修改页面
网友评论