shop--9.商品--批量操作--添加(后端)
1.插入商品信息
Dao层
public int insertProduct(Product product);
<insert id="insertProduct" parameterType="com.shop.bean.Product" useGeneratedKeys="true" keyProperty="productId" keyColumn="product_id"> INSERT INTO product(product_name, product_desc, img_addr, normal_price, promotion_price, priority, create_time, last_edit_time, status, product_category_id, shop_id) VALUES (#{productName}, #{productDesc}, #{imgAddr}, #{normalPrice}, #{promotionPrice}, #{priority}, #{createTime}, #{lastEditTime}, #{status}, #{productCategory.productCategoryId}, #{shop.shopId}) </insert>
2.批量添加商品图片信息
Dao层
public int batchInsertProductImg(List<ProductImg> productImgList);
<insert id="batchInsertProductImg" parameterType="java.util.List"> INSERT INTO product_img(img_addr, img_desc, priority, create_time, product_id) VALUES <foreach collection="list" item="productImg" index="index" separator=","> ( #{productImg.imgAddr}, #{productImg.imgDesc}, #{productImg.priority}, #{productImg.createTime}, #{productImg.productId} ) </foreach> </insert>
Service层
/** * 添加商品信息及图片处理 * @param product * @param thumbnail * @param productImgList * @return * @throws ProductOperationException */ ProductExecution addProduct(Product product, CommonsMultipartFile thumbnail, List<CommonsMultipartFile> productImgList) throws ProductOperationException;
impl
/** * 1.处理缩略图,获取缩略图的相对路径并赋值给product中的imgAddr * 2.往product中写入商品信息,获取productId * 3.结合productId,批量处理商品详情图片 * 4.将商品详情图列表批量插入product_img中 * @param product * @param thumbnail * @param productImgList * @return * @throws ProductOperationException */ @Override public ProductExecution addProduct(Product product, CommonsMultipartFile thumbnail, List<CommonsMultipartFile> productImgList) throws ProductOperationException { //空值判断 if(product != null && product.getShop() != null && product.getShop().getShopId() != null){ //给商品设置默认属性 product.setCreateTime( new Date() ); product.setLastEditTime( new Date( ) ); //设置商品状态,默认为上架 product.setStatus(1); //设置商品的缩略图 if(thumbnail != null){ addThumbnail(product, thumbnail); } try{ //插入商品信息,获得商品Id int productId = productDao.insertProduct( product ); if(productId <= 0){ throw new ProductOperationException("创建商品失败"); } } catch(Exception e){ throw new ProductOperationException( "创建商品失败" + e.toString() ); } if(productImgList != null && productImgList.size() > 0){ addProductImgList(product, productImgList); } return new ProductExecution( ProductStateEnum.SUCCESS, product); } else{ return new ProductExecution(ProductStateEnum.EMPTY); } } /** * 将商品缩略图添加到用户相对的文件夹下,并将店铺信息中的商品图片信息更新 * @param product * @param thumbnail */ public void addThumbnail(Product product, CommonsMultipartFile thumbnail){ //获取缩略图的存储途径,直接存储在店铺的文件夹下 String relativeImgPath = PathUtil.getShopImgPath(product.getShop().getShopId()); String realRelativeImgPath = ImageUtil.generateThumbnail(thumbnail, relativeImgPath); product.setImgAddr( realRelativeImgPath ); } /** * 批量添加商品详情图片到用户相对的文件夹下,并将其批量插入到数据库中 * @param product * @param productImgList */ public void addProductImgList(Product product, List<CommonsMultipartFile> productImgList){ //获取图片的存储途径,直接存储在店铺的文件夹下 String relativeImgPath = PathUtil.getShopImgPath( product.getShop().getShopId() ); List<ProductImg> productImgs = new ArrayList<>(); //遍历图片列表进行处理,并且将结果添加到productImgs中 for(CommonsMultipartFile proImg : productImgList){ String imgAddr = ImageUtil.generateNormalImg(proImg, relativeImgPath); ProductImg productImg = new ProductImg(); productImg.setImgAddr( imgAddr ); productImg.setProductId(product.getProductId()); productImg.setCreateTime( new Date( ) ); productImgs.add( productImg ); } if(productImgs.size() > 0){ try{ int effectNum = productImgDao.batchInsertProductImg( productImgs ); if(effectNum <= 0){ throw new ProductOperationException("创建商品详情图片失败"); } } catch(Exception e){ throw new ProductOperationException("创建商品详情图片失败" + e.toString()); } } }
Controller层
将前端传回来的商品信息、缩略图、详情图添加到后台数据库中
@Controller @RequestMapping("/shopadmin") public class ProductManagementController { @Autowired ProductService productService; //支持上传商品详情图的最大数量 private static final int MAXIMAGECOUNT = 6; @RequestMapping(value="/addproduct", method= RequestMethod.POST) @ResponseBody private Map<String, Object> addProduct(HttpServletRequest request) throws IOException { Map<String, Object> modelMap = new HashMap<>(); //验证码校验 if(!CodeUtil.checkVerifyCode(request)){ modelMap.put( "success", false ); modelMap.put( "errMsg", "验证码错误" ); return modelMap; } //接收前端参数变量的初始化,商品,缩略图,商品详情图片 //不懂 ObjectMapper objectMapper = new ObjectMapper(); Product product = null; String productStr = HttpServletRequestUtil.getString(request, "productStr"); CommonsMultipartFile thumbnail = null; List<CommonsMultipartFile> productImgList = new ArrayList<>( ); //在本次会话的上下文获取上传的文件 CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext() ); MultipartHttpServletRequest multipartHttpServletRequest = null; try{ //如果上传的文件有值 if(commonsMultipartResolver.isMultipart( request )){ multipartHttpServletRequest = (MultipartHttpServletRequest) request; thumbnail = (CommonsMultipartFile) multipartHttpServletRequest.getFile("thumbnail"); for(int i = 0; i < MAXIMAGECOUNT; i++){ CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartHttpServletRequest.getFile("productImg" + i); if(commonsMultipartFile != null){ productImgList.add( commonsMultipartFile ); } else { break; } } } else{ modelMap.put( "success", false ); modelMap.put( "errMsg", "上传图片不能为空" ); } } catch (Exception e){ modelMap.put( "success", false ); modelMap.put( "errMsg", e.toString() ); return modelMap; } try{ //尝试获取从前端传过来的表单String流,并借助ObjectMapper将其转化为Product实体类 product = objectMapper.readValue(productStr, Product.class); } catch(Exception e){ modelMap.put( "success", false ); modelMap.put( "errMsg", e.toString() ); return modelMap; } //若product,thumbnail(缩略图),productImgList(商品详情图片列表)不为空,则进行商品添加 if(product != null && thumbnail != null && productImgList.size() > 0){ try{ //从session中获取当前shop的id赋值给product,减少对前端数据的依赖 /*Shop currentShop = (Shop) request.getSession().getAttribute( "currentShop" ); */ Shop currentShop = new Shop(); currentShop.setShopId( 1L ); Shop shop = new Shop(); shop.setShopId(currentShop.getShopId()); product.setShop(shop); //执行添加操作 ProductExecution productExecution = productService.addProduct( product, thumbnail, productImgList ); if(productExecution.getState() == ProductStateEnum.SUCCESS.getState()){ modelMap.put( "success", true ); }else{ modelMap.put( "success", false ); modelMap.put( "errMsg", productExecution.getStateInfo() ); } } catch(ProductOperationException e){ modelMap.put( "success", false ); modelMap.put( "errMsg", e.toString() ); return modelMap; } }else{ modelMap.put( "success", false ); modelMap.put( "errMsg", "请输入商品信息" ); } return modelMap; } }