程序员社区

【校园商铺SSM-21】商品添加--Service层的实现

文章目录

      • 1. ProductService接口
      • 2. 封装ImageHolder工具类
      • 3. 改造店铺相关类
        • 3.1 改造ShopService接口
        • 3.2 改造ShopServiceImpl实现类
        • 3.3 改造ImageUtil工具类
        • 3.4 改造Controller层
        • 3.5 改造ShopServiceTest
      • 4. ProductServiceImpl实现类
      • 5. ImageUtil工具类
      • 6. ProductServiceTest测试类

1. ProductService接口

import com.imooc.o2o.dto.ImageHolder;
import com.imooc.o2o.dto.ProductExecution;
import com.imooc.o2o.entity.Product;
import com.imooc.o2o.exceptions.ProductOperationException;

import java.util.List;

public interface ProductService {
    /**
     * 1.处理缩略图
     * 2.处理商品详情图片
     * 3.添加商品信息
     * @param product 商品对象
     * @param thumbnail 缩略图文件流
     * @param thumnailName 缩略图名称
     * @param productImgList 详情图文件流
     * @param productImgNameList 详情图名称
     * @return
     * @throws ProductOperationException
     * 将缩略图的参数封装为一个类
     * 将详情图的参数封装为一个类
     */
//   ProductExecution addProuct(Product product,
//                              InputStream thumbnail,
//                              String thumnailName,
//                              List<InputStream> productImgList,
//                              List<String> productImgNameList) throws ProductOperationException;

    /**
     *
     * @param product
     * @param thumbnail
     * @param productImgHolderList
     * @return
     * @throws ProductOperationException
     */
    ProductExecution addProduct(Product product,
                               ImageHolder thumbnail,
                               List<ImageHolder> productImgHolderList) throws ProductOperationException;
}

2. 封装ImageHolder工具类

import java.io.InputStream;

public class ImageHolder {
    private String imageName;
    private InputStream image;

    public ImageHolder(String imageName, InputStream image) {
        this.imageName = imageName;
        this.image = image;
    }

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    public InputStream getImage() {
        return image;
    }

    public void setImage(InputStream image) {
        this.image = image;
    }
}

3. 改造店铺相关类

3.1 改造ShopService接口

package com.imooc.o2o.service;

import com.imooc.o2o.dto.ImageHolder;
import com.imooc.o2o.dto.ShopExecution;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.exceptions.ShopOperationException;

import java.io.FileNotFoundException;
import java.io.InputStream;

public interface ShopService {
    /**
     * 注册店铺信息,包括图片处理
     * @param shop
     * @param thumbnail
     * @return
     * @throws ShopOperationException
     */
    ShopExecution addShop(Shop shop, ImageHolder thumbnail) throws ShopOperationException,FileNotFoundException;

    /**
     * 通过店铺Id获取店铺信息
     * @param shopId
     * @return
     */
    Shop getByShopId(long shopId);

    /**
     * 更新店铺信息,包括对图片的处理
     * @param shop
     * @param thumbnail
     * @return
     * @throws ShopOperationException
     */
    ShopExecution modifyShop(
            Shop shop, ImageHolder thumbnail) throws ShopOperationException;
    /**
     * 根据shopCondition分页返回相应列表数据
     * @param shopCondition
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public ShopExecution getShopList(
            Shop shopCondition,int pageIndex,int pageSize);
}

3.2 改造ShopServiceImpl实现类

import com.imooc.o2o.dao.ShopDao;
import com.imooc.o2o.dto.ImageHolder;
import com.imooc.o2o.dto.ShopExecution;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.enums.ShopStateEnum;
import com.imooc.o2o.exceptions.ShopOperationException;
import com.imooc.o2o.service.ShopService;
import com.imooc.o2o.util.ImageUtil;
import com.imooc.o2o.util.PageCaculator;
import com.imooc.o2o.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Service
public class ShopServiceImpl implements ShopService {
    @Autowired
    private ShopDao shopDao;

    @Override
    public ShopExecution getShopList(Shop shopCondition, int pageIndex, int pageSize) {
        int rowIndex =
                PageCaculator.calculateRowIndex(pageIndex,pageSize);
        List<Shop> shopList =
                shopDao.queryShopList(shopCondition,rowIndex,pageSize);
        int count = shopDao.queryShopCount(shopCondition);
        ShopExecution se = new ShopExecution();
        if(shopList!=null){
            se.setShopList(shopList);
            se.setCount(count);
        }else {
            se.setState(ShopStateEnum.INNER_ERROR.getState());
        }
        return se;
    }
    /**
     * @param shop 创建的店铺
     * @param thumbnail
     * @return 返回状态信息结果
     * @throws ShopOperationException
     * 后面两个传入参数都是与图片处理有关,用于向店铺中添加shopImg信息
     */
    @Transactional//事务,方法需要事务支持
    public ShopExecution addShop(Shop shop, ImageHolder thumbnail) throws ShopOperationException,FileNotFoundException {
        //空值判断
        if (shop == null) {
            return new ShopExecution(ShopStateEnum.NULL_SHOP);
        }
        try {
            //给店铺信息赋初始值
            shop.setEnableStatus(0);//审核中,未上架
            shop.setCreateTime(new Date());
            shop.setLastEditTime(new Date());
            int effectedNum = shopDao.insertShop(shop);//添加店铺信息(将上面赋初值的信息插入到数据库表中)
            if (effectedNum <= 0) {
                throw new ShopOperationException("店铺创建失败");//事务终止并回滚
            } else {
                if (thumbnail.getImage() != null) { //判断传入的文件流是否为空,如果不为空就将图片存储到对应的目录中
                    try {
                        //根据shopId获取图片存储的相对路径
                        //根据相对路径给图片添加水印,并且存储在绝对路径中
                        addShopImg(shop,thumbnail);//存储图片
                    } catch (Exception e) {
                        throw new ShopOperationException("addShopImg error" + e.getMessage());
                    }
                    //添加店铺的时候数据库中并没有添加店铺的图片地址,因此需要更新店铺信息
                    effectedNum = shopDao.updateShop(shop);//更新店铺的图片地址
                    if (effectedNum <= 0) {
                        throw new ShopOperationException("更新图片地址失败");
                    }
                }
            }
        } catch (Exception e) {
            throw new ShopOperationException("addShop error:" + e.getMessage());
        }
        return new ShopExecution(ShopStateEnum.CHECK, shop);
    }

    @Override
    public Shop getByShopId(long shopId) {
        return shopDao.queryByShopId(shopId);
    }

    @Override
    public ShopExecution modifyShop(Shop shop,ImageHolder thumbnail) throws ShopOperationException{
        if(shop==null || shop.getShopId()==null){
            return new ShopExecution(ShopStateEnum.NULL_SHOP);
        }else{
            try {
                //1.判断是否需要处理图片(更换店铺的图片)
                if(thumbnail.getImage()!=null && thumbnail.getImageName()!=null &&!"".equals(thumbnail.getImageName())){
                    Shop tempShop = shopDao.queryByShopId(shop.getShopId());
                    //先判断店铺图片存不存在,如果存在就删除
                    if(tempShop.getShopImg()!=null){
                        ImageUtil.deleteFileOrPath(tempShop.getShopImg());
                    }
                    //生成新的店铺图片
                    addShopImg(shop,thumbnail);
                }
                //2.更新店铺信息
                shop.setLastEditTime(new Date());
                int effectedNum = shopDao.updateShop(shop);
                if(effectedNum<=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());
            }
        }
    }
    private void addShopImg(Shop shop, ImageHolder thumbnail) {
        //根据shopId获取店铺图片的相对路径
        String dest = PathUtil.getShopImagePath(shop.getShopId());
        //给图片添加水印并将图片存储在绝对值路径中,返回图片的相对值路径
        String shopImgAddr = ImageUtil.generateThumbnail(thumbnail, dest);
        shop.setShopImg(shopImgAddr);
    }
}

3.3 改造ImageUtil工具类

import com.imooc.o2o.dto.ImageHolder;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


public class ImageUtil {
    private static final Logger logger = LoggerFactory.getLogger(ImageUtil.class);
    //获取classpath路径
    private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    private static final Random r = new Random();

    /**
     * @param thumbnail
     * @param targetAddr  新的文件存储在targetAddr目录中
     * @return 处理缩略图,并返回新生成图片的相对值路径
     */
    public static String generateThumbnail(ImageHolder thumbnail, String targetAddr) {
        //获取文件的随机名称
        String realFileName = getRandomFileName();
        //获取用户上传的文件的扩展名称(文件后缀)
        String extension = getFileExtension(thumbnail.getImageName());

        //创建图片的存储目录(这个目录包括根目录加上相对目录)
        makeDirPath(targetAddr);
        //图片的相对目录
        String relativeAddr = targetAddr +realFileName + extension;
        logger.debug("图片的相对路径:"+relativeAddr);
        //图片的绝对目录
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
        logger.debug("图片完整路径:"+dest.getAbsolutePath());
        try {
            //可以传入文件,也可以传入图片流
            Thumbnails.of(thumbnail.getImage()).size(200, 200)
                    .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File(basePath + "watermark.jpg")),0.25f)
                    .outputQuality(0.8f).toFile(dest);
        }catch (IOException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return relativeAddr;
    }

    /**
     * 创建目标路径所涉及到的目录
     * 如:upload/item/shop/xxx.jpg,那么upload,item,shop这三个文件夹都得自动创建
     * @param targetAddr
     */
    private static void makeDirPath(String targetAddr) {
        String realFileParentPath = PathUtil.getImgBasePath()+targetAddr;
        File dirPath = new File(realFileParentPath);
        if(!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }

    /**
     * 生成随机文件名,当前年月日小时分钟秒+五位随机数
     */
    public static String getRandomFileName() {
        //获取随机的五位数
        int rannum = r.nextInt(89999) + 10000;
        //获取当前的年月日时分秒
        String nowTimeStr = sDateFormat.format(new Date());
        //随机文件名
        return nowTimeStr+rannum;
    }

    /**
     * 获取输入文件的扩展名
     * @throws IOException
     */
    private static String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    public static void main(String[] args) throws IOException {
        //获取Classpath的路径
        String basePath = Thread.currentThread()
                .getContextClassLoader()
                .getResource("").getPath();
        System.out.println(basePath);
        //要处理的图片
        Thumbnails.of(new File("F:/XiaoYuanShangPu/xiaohuangren.jpg"))
                //输出图片的长和宽
                .size(800, 600)
                //给图片添加水印,三个参数
                .watermark(                        //水印位置
                        Positions.BOTTOM_RIGHT,
                        //水印图片的路径
                        ImageIO.read(new File(basePath + "watermark.jpg")),
                        //水印透明度
                        0.75f)
                //压缩80%
                .outputQuality(0.8f)
                //输出添加水印后图片的位置
                .toFile("F:/XiaoYuanShangPu/xiaohuangrennew.jpg");
    }

    /**
     * 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 files[] = fileOrPath.listFiles();
                //递归删除目录下面的文件
                for(int i=0;i<files.length;i++){
                    files[i].delete();
                }
            }
            fileOrPath.delete();
        }
    }
}

3.4 改造Controller层

@RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> modifyshop(HttpServletRequest request) {
    Map<String, Object> modelMap = new HashMap<String, Object>();
    // 0. 验证码校验
    if (!CodeUtil.verifyCode(request)) {
        modelMap.put("success", false);
        modelMap.put("errMsg", "验证码不正确");
        return modelMap;
    }
    // 1. 接收并转换相应的参数,包括shop信息和图片信息
    // 1.1 shop信息
    // shopStr 是和前端约定好的参数值,后端从request中获取request这个值来获取shop的信息
    String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
    // 使用jackson-databind 将json转换为pojo
    ObjectMapper mapper = new ObjectMapper();
    Shop shop = null;
    try {
        // 将json转换为pojo
        shop = mapper.readValue(shopStr, Shop.class);
    } catch (Exception e) {
        e.printStackTrace();
        // 将错误信息返回给前台
        modelMap.put("success", false);
        modelMap.put("errMsg", e.getMessage());
        return modelMap;
    }

    // 1.2 图片信息 基于Apache Commons FileUpload的文件上传 ( 修改商铺信息 图片可以不更新)
    // Spring MVC中的 图片存在CommonsMultipartFile中
    CommonsMultipartFile shopImg = null;
    // 从request的本次会话中的上线文中获取图片的相关内容
    CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    if (commonsMultipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // shopImg是和前端约定好的变量名
        shopImg = (CommonsMultipartFile) multipartRequest.getFile("shopImg");
    }

    // 2. 修改店铺
    if (shop != null && shop.getShopId() != null) {
        // Session 部分的 PersonInfo 修改商铺是不需要的设置的。
        // 修改店铺
        ShopExecution se = null;
        try {
            if (shopImg != null) {
                ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(),shopImg.getInputStream());
                se = shopService.modifyShop(shop,imageHolder);
            } else {
                se = shopService.modifyShop(shop, null);
            }
            // 成功
            if (se.getState() == ShopStateEnum.SUCCESS.getState()) {
                modelMap.put("success", true);
                modelMap.put("errMsg", "修改成功");
            } else {
                modelMap.put("success", false);
                modelMap.put("errMsg", se.getStateInfo());
            }
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.put("success", false);
            modelMap.put("errMsg", "ModifyShop Error");
        }
    } else {
        // 将错误信息返回给前台
        modelMap.put("success", false);
        modelMap.put("errMsg", "ShopId不合法");
    }
    return modelMap;
}
/**
 * 店铺注册
 * @param request
 * @return
 */
@RequestMapping(value="/registshop",method = RequestMethod.POST)
@ResponseBody
private Map<String,Object> registerShop(HttpServletRequest request){
    Map<String,Object>  modelMap=new HashMap<String,Object>();
    //先判断验证码是否正确
    if (!CodeUtil.verifyCode(request)){//当验证码错误时
        modelMap.put("success",false);
        modelMap.put("errMsg","输入了错误的验证码");
        return modelMap;
    }
    //1.接受转换相应的参数,包括店铺信息和店铺图片信息
    String shopStr = HttpServletRequestUtil.getString(request,"shopStr");//通过转换工具类将前端传来的数据转为字符串
    ObjectMapper mapper=new ObjectMapper();//获取处理json的对象
    //定义一个Shop实体类来接收起前端传来的信息
    Shop shop=null;
    try{
        shop=mapper.readValue(shopStr,Shop.class);//将传入的shopStr转为Shop对象并完成赋值
    }catch (Exception e){//出错后输出错误信息
        modelMap.put("success",false);
        modelMap.put("errMsg",e.getMessage());
        return modelMap;
    }

    //操作添加图片
    CommonsMultipartFile shopImg=null;//spring自带
    CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver(
            request.getSession().getServletContext()
    );//解析request传来的文件的,通过本次会话的上下文获取相关文件上传的内容
    if (commonsMultipartResolver.isMultipart((request))) {//如果有上传的文件流
        MultipartHttpServletRequest multipartHttpServletRequest= (MultipartHttpServletRequest) request;//这样就能提取出request中的文件流了
        shopImg=(CommonsMultipartFile)multipartHttpServletRequest.getFile("shopImg");//(这个字符串"shopImg"是前端传来的),得到文件
    }else {//如果不具备图片
        modelMap.put("success",false);
        modelMap.put("errMsg","上传图片不能为空");
        return modelMap;
    }
    // 2.注册店铺
    if (shop!=null&&shopImg!=null) {//如果接受完相应的参数
        PersonInfo owner=(PersonInfo)request.getSession().getAttribute("user");//owner的信息可以通过session获取
        shop.setOwner(owner);
        ShopExecution shopExecution= null;//不能直接传文件,因为CommonsMultipartFile和File不能直接转换
        try {
            ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(),shopImg.getInputStream());
            shopExecution = shopService.addShop(shop,imageHolder);
            if (shopExecution.getState()== ShopStateEnum.CHECK.getState()){//如果操作成功
                modelMap.put("success",true);
                List<Shop> shopList = (List<Shop>)request.getSession().getAttribute("shopList");
                if(shopList==null||shopList.size()==0){
                    shopList = new ArrayList<Shop>();
                }
                shopList.add(shopExecution.getShop());
                request.getSession().setAttribute("shopList",shopList);
            }else {
                modelMap.put("success",false);
                modelMap.put("errMsg",shopExecution.getStateInfo());
                return modelMap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return modelMap;
    }else{
        modelMap.put("success",false);
        modelMap.put("errMsg","请输入店铺信息");
        return modelMap;
    }
}

3.5 改造ShopServiceTest

    @Test
    public void testAddShop() throws ShopOperationException, FileNotFoundException {
        Shop shop = new Shop();
        PersonInfo owner = new PersonInfo();
        Area area = new Area();
        ShopCategory shopCategory = new ShopCategory();

        owner.setUserId(2L);
        area.setAreaId(2);
        shopCategory.setShopCategoryId(1L);
        shop.setOwner(owner);
        shop.setArea(area);
        shop.setShopCategory(shopCategory);

        shop.setShopName("咖啡店");
        shop.setShopDesc("出售咖啡");
        shop.setShopAddr("北京");
        shop.setPhone("7632554");
        shop.setCreateTime(new Date());
        shop.setEnableStatus(ShopStateEnum.CHECK.getState());
        shop.setAdvice("审核中");
        //要传入的文件
        File shopImg = new File("F:/XiaoYuanShangPu/xiaohuangren.jpg");
        //将图片文件封装为文件流
        InputStream is = new FileInputStream(shopImg);
        ImageHolder imageHolder = new ImageHolder("xiaohuangren.jpg",is);
        //添加图片信息
        ShopExecution shopException = shopService.addShop(shop,imageHolder);
        assertEquals(ShopStateEnum.CHECK.getState(),shopException.getState());
    }

    @Test
    public void testModifyShop() throws ShopOperationException,FileNotFoundException{
        Shop shop = new Shop();
        shop.setShopId(143L);
        shop.setShopName("修改后的店铺名称:");
        shop.setEnableStatus(1);
        //要传入的文件
        File shopImg = new File("F:/XiaoYuanShangPu/dabai.jpg");
        //将图片文件封装为文件流
        InputStream is = new FileInputStream(shopImg);
        ImageHolder imageHolder = new ImageHolder("dabai.jpg",is);
        //更改图片信息
        ShopExecution shopExecution = shopService.modifyShop(shop,imageHolder);
        System.out.println(shopExecution.getShop().getShopImg());
    }

4. ProductServiceImpl实现类

import com.imooc.o2o.dao.ProductDao;
import com.imooc.o2o.dao.ProductImgDao;
import com.imooc.o2o.dto.ImageHolder;
import com.imooc.o2o.dto.ProductExecution;
import com.imooc.o2o.entity.Product;
import com.imooc.o2o.entity.ProductImg;
import com.imooc.o2o.enums.ProductStateEnum;
import com.imooc.o2o.exceptions.ProductOperationException;
import com.imooc.o2o.service.ProductService;
import com.imooc.o2o.util.ImageUtil;
import com.imooc.o2o.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@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中
     * @param product
     * @param thumbnail
     * @param productImgHolderList
     * @return
     * @throws ProductOperationException
     */
    @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 (ProductOperationException e) {
                throw new ProductOperationException("创建商品失败"+e.toString());
            }
            //如果商品详情图不为空就添加
            if(productImgHolderList !=null && productImgHolderList.size()>0){
                addProductImgList(product,productImgHolderList);
            }
            return new ProductExecution(ProductStateEnum.SUCCESS,product);
        }else{
            return new ProductExecution(ProductStateEnum.EMPTY);
        }
    }

    /**
     * 添加缩略图
     * @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);
    }

    /**
     * 批量添加图片
     * @param product
     * @param productImgHolderList
     */
    private void addProductImgList(Product product, List<ImageHolder> productImgHolderList) {
        //获取图片存储路径,这里直接存储在相应店铺的文件夹下面
        String dest = PathUtil.getShopImagePath(product.getShop().getShopId());
        List<ProductImg> productImgList = new ArrayList<ProductImg>();
        //遍历图片依次去处理并添加到productImg的实体类中
        for(ImageHolder productImgHolder:productImgHolderList){
            //得到图片的相对路径
            String imgAddr = ImageUtil.generateNormalImg(productImgHolder,dest);
            ProductImg productImg = new ProductImg();
            productImg.setImgAddr(imgAddr);
            productImg.setProductImgId(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());
            }
        }
    }
}

5. ImageUtil工具类

在ImageUtil工具类中添加:

    /**
     *
     * @param thumbnail
     * @param targetAddr
     * @return
     */
    public static String generateNormalImg(ImageHolder thumbnail,String targetAddr){
        //获取文件的随机名称
        String realFileName = getRandomFileName();
        //获取用户上传的文件的扩展名称(文件后缀)
        String extension = getFileExtension(thumbnail.getImageName());

        //创建图片的存储目录(这个目录包括根目录加上相对目录)
        makeDirPath(targetAddr);
        //图片的相对目录
        String relativeAddr = targetAddr +realFileName + extension;
        logger.debug("图片的相对路径:"+relativeAddr);
        //图片的绝对目录
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
        logger.debug("图片完整路径:"+dest.getAbsolutePath());
        try {
            //可以传入文件,也可以传入图片流
            Thumbnails.of(thumbnail.getImage()).size(337, 640)
                    .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File(basePath + "watermark.jpg")),0.25f)
                    .outputQuality(0.9f).toFile(dest);
        }catch (IOException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return relativeAddr;
    }

6. ProductServiceTest测试类

public class ProductServiceTest extends BaseTest {
    @Autowired
    private ProductService productService;

    @Test
    public void testAddProduct() throws ShopOperationException, FileNotFoundException {
        Shop shop1 = new Shop();
        shop1.setShopId(143L);

        ProductCategory pc1 = new ProductCategory();
        pc1.setProductCategoryId(9L);

        Product product = new Product();
        product.setProductName("测试商品1");
        product.setProductDesc("测试商品1");
        product.setPriority(1);
        product.setCreateTime(new Date());
        product.setShop(shop1);
        product.setProductCategory(pc1);
        product.setEnableStatus(ProductStateEnum.SUCCESS.getState());

        //创建缩略图文件流
        File thumbnailFile = new File("F:/XiaoYuanShangPu/xiaohuangren.jpg");
        InputStream is = new FileInputStream(thumbnailFile);
        ImageHolder thumbnail = new ImageHolder(thumbnailFile.getName(), is);
        //创建两个商品详情图片文件流并将它们添加到详情图列表中
        File productImg1 = new File("F:/XiaoYuanShangPu/xiaohuangren.jpg");
        InputStream is1 = new FileInputStream(productImg1);
        File productImg2 = new File("F:/XiaoYuanShangPu/dabai.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.addProduct(product,thumbnail,productImgList);
        assertEquals(ProductStateEnum.SUCCESS.getState(),pe.getState());
    }
}

在这里插入图片描述
在这里插入图片描述

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 【校园商铺SSM-21】商品添加--Service层的实现

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区