1.商品编辑之Service层
1.1 Service层需要2个接口方法:
- getProductById:去编辑之前先获取商品的信息
- modifyProduct:修改商品
package com.csj2018.o2o.service;
import java.util.List;
import com.csj2018.o2o.dto.ImageHolder;
import com.csj2018.o2o.dto.ProductExecution;
import com.csj2018.o2o.entity.Product;
import com.csj2018.o2o.exceptions.ProductOperationException;
public interface ProductService {
/**
* 查询商品列表并分页,可输入的条件有:商品名(模糊),商品状态,店铺id,商品类别
* @param productCondition
* @param pageIndex
* @param pageSize
* @return
*/
ProductExecution getProductList(Product productCondition, int pageIndex, int pageSize);
/**
* 8-7 通过商品id查询唯一的商品信息
* @param productId
* @return
*/
Product getProductById(long productId);
/**
* 添加商品信息以及图片处理
* @param product
* @param thumbnail 缩略图
* @param productImgList 详情图
* @return
* @throws ProductOperationException
*/
ProductExecution addProduct(Product product, ImageHolder thumbnail, List<ImageHolder> productImgList) throws ProductOperationException;
/**
* 8-7 修改商品信息以及图片处理
* @param product
* @param thumbnail
* @param productImgList
* @return
* @throws ProductOperationException
*/
ProductExecution modifyProduct(Product product, ImageHolder thumbnail, List<ImageHolder> productImgList) throws ProductOperationException;
}
1.2.商品编辑Service实现类
package com.csj2018.o2o.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.csj2018.o2o.dao.ProductDao;
import com.csj2018.o2o.dao.ProductImgDao;
import com.csj2018.o2o.dto.ImageHolder;
import com.csj2018.o2o.dto.ProductExecution;
import com.csj2018.o2o.entity.Product;
import com.csj2018.o2o.entity.ProductImg;
import com.csj2018.o2o.enums.ProductStateEnum;
import com.csj2018.o2o.exceptions.ProductOperationException;
import com.csj2018.o2o.service.ProductService;
import com.csj2018.o2o.util.*;
@Service
public class ProductServiceImpl implements ProductService{
@Autowired
private ProductDao productDao;
@Autowired
private ProductImgDao productImgDao;
/*
* 1.处理缩略图,获取缩略图相对路径并赋值给product
* 2.往tb_product写入商品信息,获取productId
* 3.结合productId批量处理商品详情图
* 4.将商品详情图列表批量插入tb_product_img中
* 通过spring的事务管理去执行这4不操作,任何一步出错就回滚,不会往表里写入
*/
@Override
@Transactional
public ProductExecution addProduct(Product product, ImageHolder thumbnail, List<ImageHolder> productImgHolderList)
throws ProductOperationException {
//空值判断
if(product != null && product.getShop() != null && product.getShop().getShopId() != null) {
//给商品设置默认属性
product.setCreateTime(new Date());
product.setLastEditTime(new Date());
//默认为上架的状态
product.setEnableStatus(1);
//若商品缩略图不为空,则添加缩略图信息到商品
if(thumbnail != null) {
addThumbnail(product,thumbnail);
}
try {
int effectedNum = productDao.insertProduct(product);
if(effectedNum <= 0) {
throw new ProductOperationException("创建商品失败");
}
}catch (Exception e) {
throw new ProductOperationException("创建商品失败:"+e.toString());
}
//若商品详情图不为空,则向tb_product_img添加商品详情图
if(productImgHolderList != null && productImgHolderList.size() >0) {
addProductImgList(product,productImgHolderList);
}
return new ProductExecution(ProductStateEnum.SUCCESS,product);
}else {
//传参为空,则返回控制错误信息
return new ProductExecution(ProductStateEnum.EMPTY);
}
}
/**
* 向product对象添加缩略图
* @param product
* @param thumbnail
*/
private void addThumbnail(Product product, ImageHolder thumbnail) {
String dest = PathUtil.getShopImagePath(product.getShop().getShopId());
String thumbnailAddr = ImageUtil.generateThumbnail(thumbnail, dest);
product.setImgAddr(thumbnailAddr);
}
private void addProductImgList(Product product, List<ImageHolder> productImgHolderList) {
//获取图片存储路径,这里直接存放到相应店铺的文件夹下,同缩略图
String dest = PathUtil.getShopImagePath(product.getShop().getShopId());
List<ProductImg> productImgList = new ArrayList<ProductImg>();
//遍历,获得详情图片列表
for(ImageHolder productImgHolder:productImgHolderList) {
String imgAddr = ImageUtil.generateNormalImg(productImgHolder, dest);
ProductImg productImg = new ProductImg();
productImg.setImgAddr(imgAddr);
productImg.setProductId(product.getProductId());
productImg.setCreateTime(new Date());
productImgList.add(productImg);
}
if(productImgList.size() > 0) {
try {
int effectedNum = productImgDao.batchInsertProductImg(productImgList);
if(effectedNum <= 0) {
throw new ProductOperationException("创建商品详情图片失败");
}
}catch (Exception e) {
throw new ProductOperationException("创建商品详情图片失败:"+e.toString());
}
}
}
@Override
public ProductExecution getProductList(Product productCondition, int pageIndex, int pageSize) {
// TODO Auto-generated method stub
return null;
}
@Override
public Product getProductById(long productId) {
return productDao.queryProductById(productId);
}
//1.若缩略图参数有值,则处理缩略图
//2.若原先存在缩略图则先删除再添加新图,之后获取缩略图相对路径并赋值给product
//3.将tb_product_img下面的该商品原先的商品详情记录全部清除
//4.更新tb_product,tb_product_img的信息
@Override
@Transactional
public ProductExecution modifyProduct(Product product, ImageHolder thumbnail, List<ImageHolder> productImgList)
throws ProductOperationException {
//空值判断。存放商品缩略图和详情图需要用到shopId做路径,因此需要针对shop做空值判断
if(product != null && product.getShop() != null && product.getShop().getShopId() != null) {
//给商品设置添加默认属性
product.setLastEditTime(new Date());
//若商品缩略图不为空且原有缩略图不为空,则删除原有缩略图并添加
if(thumbnail != null) {
//先获取一遍原有信息,因为原来的信息里有原图片地址
Product tempProduct = productDao.queryProductById(product.getProductId());
if(tempProduct.getImgAddr() != null) {
//从磁盘中删除缩略图
ImageUtil.deleteFileOfPath(tempProduct.getImgAddr());
}
addThumbnail(product,thumbnail);
}
//如果有新存入的商品详情图,则将原先的删除,并添加新的图片
if(productImgList != null && productImgList.size() > 0) {
deleteProductImgList(product.getProductId());
addProductImgList(product,productImgList);
}
try {
//更新商品信息
int effectedNum = productDao.updateProduct(product);
if(effectedNum <= 0) {
throw new ProductOperationException("更新商品信息失败");
}
return new ProductExecution(ProductStateEnum.SUCCESS,product);
}catch (Exception e) {
throw new ProductOperationException("更新商品信息失败:"+e.toString());
}
}else {
return new ProductExecution(ProductStateEnum.EMPTY);
}
}
/**
* 删除某个商品下的所有详情图
* @param productId
*/
private void deleteProductImgList(long productId) {
//根据productId获取原来的图片
List<ProductImg> productImgList = productImgDao.queryProductImgList(productId);
//从磁盘删除原来的图片
for(ProductImg productImg:productImgList) {
ImageUtil.deleteFileOfPath(productImg.getImgAddr());
}
//从数据库删除原有图片的信息
productImgDao.deleteProductImgByProductId(productId);
}
}
1.3.针对ModifyProduct的单元测试
package com.csj2018.o2o.service;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.csj2018.o2o.BaseTest;
import com.csj2018.o2o.dto.ImageHolder;
import com.csj2018.o2o.dto.ProductExecution;
import com.csj2018.o2o.entity.Product;
import com.csj2018.o2o.entity.ProductCategory;
import com.csj2018.o2o.entity.Shop;
import com.csj2018.o2o.enums.ProductStateEnum;
import com.csj2018.o2o.exceptions.ProductOperationException;
import com.csj2018.o2o.exceptions.ShopOperationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ProductServiceTest extends BaseTest{
@Autowired
private ProductService productService;
@Test
@Ignore
public void testAddProduct() throws ProductOperationException,FileNotFoundException{
//创建shopID为1且productCategory为1的商品实例,并给其成员变量赋值
Product product = new Product();
Shop shop = new Shop();
shop.setShopId(1L);
ProductCategory pc = new ProductCategory();
pc.setProductCategoryId(10L);
product.setShop(shop);
product.setProductCategory(pc);
product.setProductName("测试商品1");
product.setProductDesc("测试商品1");
product.setPriority(20);
product.setCreateTime(new Date());
product.setEnableStatus(1);
//创建缩略图
File thumbnailFile = new File("/Users/chenshanju/Downloads/Y61.jpeg");
InputStream is = new FileInputStream(thumbnailFile);
ImageHolder thumbnail = new ImageHolder(thumbnailFile.getName(),is);
//创建2个详情图片
File productImg1 = new File("/Users/chenshanju/Downloads/Prado.jpg");
InputStream is1 = new FileInputStream(thumbnailFile);
File productImg2 = new File("/Users/chenshanju/Downloads/Pajero.jpg");
InputStream is2 = new FileInputStream(thumbnailFile);
List<ImageHolder> productImgList = new ArrayList<ImageHolder>();
productImgList.add(new ImageHolder(productImg1.getName(),is1));
productImgList.add(new ImageHolder(productImg2.getName(),is2));
ProductExecution pe = productService.addProduct(product, thumbnail, productImgList);
assertEquals(ProductStateEnum.SUCCESS.getState(),pe.getState());
}
//8-7
@Test
public void testModifyProduct() throws ShopOperationException,FileNotFoundException{
//创建shopId为1且productCategory为1的商品示例,并给其成员变量赋值
Product product = new Product();
Shop shop = new Shop();
shop.setShopId(1L);
ProductCategory pc = new ProductCategory();
pc.setProductCategoryId(12L);
product.setProductId(1L);
product.setShop(shop);
product.setProductCategory(pc);
product.setProductName("正式的商品");
product.setProductDesc("正式的商品");
//创建缩略图文件流
File thumbnailFile = new File("/Users/chenshanju/Downloads/tq91.jpg");
InputStream is = new FileInputStream(thumbnailFile);
ImageHolder thumbnail = new ImageHolder(thumbnailFile.getName(),is);
//创建2个商品详情图文件流并将它们添加到详情图列表中
File productImg1 = new File("/Users/chenshanju/Downloads/Pajero.jpg");
InputStream is1 = new FileInputStream(productImg1);
File productImg2 = new File("/Users/chenshanju/Downloads/Prado.jpg");
InputStream is2 = new FileInputStream(productImg2);
List<ImageHolder> productImgList = new ArrayList<>();
productImgList.add(new ImageHolder(productImg1.getName(),is1));
productImgList.add(new ImageHolder(productImg2.getName(),is2));
//添加商品并验证
ProductExecution pe = productService.modifyProduct(product, thumbnail, productImgList);
assertEquals(ProductStateEnum.SUCCESS.getState(),pe.getState());
}
}
2.Controller
package com.csj2018.o2o.web.shopadmin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.csj2018.o2o.dto.ImageHolder;
import com.csj2018.o2o.dto.ProductExecution;
import com.csj2018.o2o.entity.Product;
import com.csj2018.o2o.entity.ProductCategory;
import com.csj2018.o2o.entity.Shop;
import com.csj2018.o2o.enums.ProductStateEnum;
import com.csj2018.o2o.service.ProductCategoryService;
import com.csj2018.o2o.service.ProductService;
import com.csj2018.o2o.util.CodeUtil;
import com.csj2018.o2o.util.HttpServletRequestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
@RequestMapping("/shopadmin")
public class ProductManagementController {
@Autowired
private ProductService productService;
@Autowired
private ProductCategoryService productCategoryService;
//支持上传图片详情图的最大数值
private static final int IMAGEMAXCOUNT = 6;
@RequestMapping(value="/addproduct",method=RequestMethod.POST)
@ResponseBody
private Map<String,Object> addProduct(HttpServletRequest request){
Map<String, Object> modelMap = new HashMap<String,Object>();
//验证码校验
if(!CodeUtil.checkVerifyCode(request)) {
modelMap.put("success", false);
modelMap.put("errMsg", "输入了错误的验证码");
return modelMap;
}
//接收前端参数的变量的初始化,包括商品、缩略图、详情图列表实体类
ObjectMapper mapper = new ObjectMapper();
Product product = null;
String productStr = HttpServletRequestUtil.getString(request, "productStr");
MultipartHttpServletRequest multipartRequest = null;
ImageHolder thumbnail = null;
List<ImageHolder> productImgList = new ArrayList<ImageHolder>();
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
try {
//若请求中存在文件流,则取出相关的文件(包括缩略图和详情图)
if(multipartResolver.isMultipart(request)) {
multipartRequest = (MultipartHttpServletRequest) request;
//取出缩略图并构建ImageHolder的对象
CommonsMultipartFile thumbnailFile = (CommonsMultipartFile) multipartRequest.getFile("thumbnail");
if(thumbnailFile != null) {
thumbnail = handleImage(request,thumbnail,productImgList);
}
}else {
modelMap.put("success", false);
modelMap.put("errMsg", "上传图片不为空");
return modelMap;
}
}catch (Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.toString());
return modelMap;
}
try {
//
product = mapper.readValue(productStr,Product.class);
}catch(Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.toString());
return modelMap;
}
//若product信息,缩略图、详情图不为空,则开始进行商品添加操作
if(product != null && thumbnail != null &&productImgList.size() != 0) {
try {
//从session中获取当前店铺的ID,并赋值给product,减少对前端数据的依赖
Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
product.setShop(currentShop);
//执行添加操作
ProductExecution pe = productService.addProduct(product, thumbnail, productImgList);
if(pe.getState() == ProductStateEnum.SUCCESS.getState()) {
modelMap.put("success", true);
}else {
modelMap.put("success", false);
modelMap.put("errMsg", pe.getStateInfo());
}
}catch (RuntimeException e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.toString());
return modelMap;
}
}else {
modelMap.put("success",false);
modelMap.put("errMsg", "请输入商品信息");
}
return modelMap;
}
/**
* 8-7
* @param productId
* @return
*/
@RequestMapping(value="/getproductbyid", method=RequestMethod.GET)
@ResponseBody
private Map<String,Object> getProductById(@RequestParam Long productId){
Map<String, Object> modelMap = new HashMap<>();
//非空判断
if(productId > -1) {
//获取商品信息
Product product = productService.getProductById(productId);
System.out.println(product.getShop().getShopId());
//获取该店铺下的商品类别列表
List<ProductCategory> productCategoryList = productCategoryService.getProductCategoryList(product.getShop().getShopId());
modelMap.put("product", product);
modelMap.put("productCategoryList", productCategoryList);
modelMap.put("success", true);
}else {
modelMap.put("success", false);
modelMap.put("errMsg", "empty productId");
}
return modelMap;
}
@RequestMapping(value="/modifyproduct", method=RequestMethod.POST)
@ResponseBody
private Map<String,Object> modifyProduct(HttpServletRequest request){
Map<String, Object> modelMap = new HashMap<String, Object>();
//是商品编辑时候调用,还是上下架操作时候调用
//若为前者则进行验证码判断,后者则跳过验证码判断
boolean statusChange = HttpServletRequestUtil.getBoolean(request, "statusChange");
//验证码判断
if(!statusChange && !CodeUtil.checkVerifyCode(request)) {
modelMap.put("success", false);
modelMap.put("errMsg", "输入了错误的验证码");
return modelMap;
}
//接收前端参数的变量的初始化,包括商品,缩略图,详情图列表实体类
ObjectMapper mapper = new ObjectMapper();
Product product = null;
ImageHolder thumbnail = null;
List<ImageHolder> productImgList = new ArrayList<ImageHolder>();
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//若请求中存在文件流,则取出相关的文件(包括缩略图和详情图)
try {
if(multipartResolver.isMultipart(request)) {
thumbnail = handleImage(request, thumbnail, productImgList);
}
}catch (Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.toString());
return modelMap;
}
try {
String productStr = HttpServletRequestUtil.getString(request, "productStr");
//尝试获取从前端传过来的表单String流,并将其转化为Product对象
product = mapper.readValue(productStr, Product.class);
}catch(Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.toString());
return modelMap;
}
//非空判断
if(product != null) {
try {
//从session中获取当前店铺的ID并赋值给product,减少对前端数据的依赖
Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
product.setShop(currentShop);
//开始进行商品信息变更操作
ProductExecution pe = productService.modifyProduct(product, thumbnail, productImgList);
if(pe.getState() == ProductStateEnum.SUCCESS.getState()) {
modelMap.put("success", true);
}else {
modelMap.put("false", false);
modelMap.put("errMsg", pe.getStateInfo());
}
}catch(RuntimeException e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.toString());
return modelMap;
}
}
return modelMap;
}
private ImageHolder handleImage(HttpServletRequest request, ImageHolder thumbnail, List<ImageHolder> productImgList) throws IOException{
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//取出缩略图并构建ImageHolder对象
CommonsMultipartFile thumbnailFile = (CommonsMultipartFile) multipartRequest.getFile("thumbnail");
if(thumbnailFile != null) {
thumbnail = new ImageHolder(thumbnailFile.getOriginalFilename(), thumbnailFile.getInputStream());
}
//取出详情图并构建List<ImageHolder>列表对象,最多支持6张图片上传
for(int i=0;i<IMAGEMAXCOUNT;i++) {
CommonsMultipartFile productImgFile = (CommonsMultipartFile) multipartRequest.getFile("productImg"+i);
if(productImgFile != null) {
//若取出的第i个详情图片流不为空,则将其加入详情图列表
ImageHolder productImg = new ImageHolder(productImgFile.getOriginalFilename(),productImgFile.getInputStream());
productImgList.add(productImg);
}else {
//若取出的第i个图片文件流为空,则终止循环
break;
}
}
return thumbnail;
}
}
3.前端验证
1.session中用到了currentShop,因此先访问商品管理页 http://127.0.0.1:18080/o2o/shopadmin/shopmanagement?shopId=1
2.进入商品编辑页 http://127.0.0.1:18080/o2o/shopadmin/productoperation?productId=1
问题
1对 getProductById进行调用时出错。
是因为mapper文件未将shop返回
2.更新商品失败
是因为现价拼写错误
<?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.csj2018.o2o.dao.ProductDao"><!-- 对应接口类名 -->
<resultMap id="productMap" type="com.csj2018.o2o.entity.Product">
<id column="product_id" property="productId" />
<result column="product_name" property="productName" />
<result column="product_desc" property="productDesc" />
<result column="img_addr" property="imgAddr" />
<result column="normal_price" property="normalPrice" />
<result column="promotion_price" property="promotionPrice" />
<result column="priority" property="priority" />
<result column="create_time" property="createTime" />
<result column="last_edit_time" property="lastEditTime" />
<result column="enable_status" property="enableStatus" />
<association property="productCategory" column="product_category_id" javaType="com.csj2018.o2o.entity.ProductCategory">
<id column="product_category_id" property="productCategoryId" />
<result column="product_category_name" property="productCategoryName" />
</association>
<association property="shop" column="shop_id" javaType="com.csj2018.o2o.entity.Shop">
<id column="shop_id" property="shopId" />
<result column="shop_id" property="shopId" />
</association>
<collection property="productImgList" column="product_id" ofType="com.csj2018.o2o.entity.ProductImg">
<id column="product_img_id" property="productImgId" />
<result column="detail_img" property="imgAddr" /><!-- 有疑问,为什么不是img_addr -->
<result column="img_desc" property="imgDesc" />
<result column="priority" property="priority" />
<result column="create_time" property="createTime" />
<result column="product_id" property="productId" />
</collection>
</resultMap>
<select id="queryProductById" resultMap="productMap" parameterType="long">
select
p.product_id, p.product_name, p.product_desc, p.img_addr, p.normal_price, p.promotion_price, p.priority,
p.create_time, p.last_edit_time, p.enable_status, p.product_category_id, p.shop_id,
pm.product_img_id, pm.img_addr as detail_img, pm.img_desc, pm.priority, pm.create_time
from tb_product p left join tb_product_img pm
on p.product_id = pm.product_id
where p.product_id = #{productId}
order by pm.priority desc
</select>
<update id="updateProduct" parameterType="com.csj2018.o2o.entity.Product" keyProperty="product_id" useGeneratedKeys="true">
update tb_product
<set>
<if test="productName != null">product_name = #{productName},</if>
<if test="productDesc != null">product_desc = #{productDesc},</if>
<if test="imgAddr != null">img_addr = #{imgAddr},</if>
<if test="normalPrice != null" >normal_price = #{normalPrice},</if>
<if test="promotionPrice != null">promotion_price = #{promotionPrice},</if>
<if test="priority != null">priority = #{priority},</if>
<if test="lastEditTime != null">last_edit_time = #{lastEditTime},</if>
<if test="enableStatus != null">enable_status = #{enableStatus},</if>
<if test="productCategory != null and productCategory.productCategoryId != null">product_category_id = #{productCategory.productCategoryId}</if>
</set>
where product_id = #{productId} and shop_id = #{shop.shopId}<!--shop_id = #{shop.shopId}保证了不会操作别的店铺的商品 -->
</update>
<insert id="insertProduct" parameterType="com.csj2018.o2o.entity.Product" useGeneratedKeys="true" keyProperty="productId" keyColumn="product_id">
insert into tb_product(
product_name,product_desc,img_addr,normal_price,promotion_price,
priority,create_time,last_edit_time,enable_status,product_category_id,shop_id
)values(
#{productName},#{productDesc},#{imgAddr},#{normalPrice},#{promotionPrice},
#{priority},#{createTime},#{lastEditTime},#{enableStatus},#{productCategory.productCategoryId},#{shop.shopId}
)
</insert>
</mapper>