实战SSM_O2O商铺_34【商品】商品编辑之Controller层的实现

2021-08-17 14:32:33 浏览数 (2)

文章目录

  • 概述
  • ProductController
  • 单元测试
  • Github地址

概述

在完成了 实战SSM_O2O商铺_33【商品】商品编辑之Service层的实现之后,我们继续来实现Controller层的代码部分。

主要逻辑:

  • 根据前端url中productId ,调用service层的接口获取product信息,以便前端能在商品编辑页面展示对应的数据
  • 修改商品

ProductController

代码语言:javascript复制
/**
	 * 
	 * 
	 * @Title: getProductById
	 * 
	 * @Description: 因为只需要传入productId,使用@RequestParam注解。
	 *               同时也无需传入HttpServletRequest,用不到
	 * 
	 *               根据页面原型,不仅要加载prodcut的信息,还需要加载对应的目录信息。
	 * 
	 * @param productId
	 * 
	 * @return: Map
	 */
	@RequestMapping(value = "/getproductbyid", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getProductById(@RequestParam long productId) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (productId > -1) {
			Product product = productService.queryProductById(productId);
			List<ProductCategory> productCategoryList = productCategoryService.queryProductCategoryList(product.getShop().getShopId());
			modelMap.put("product", product);
			modelMap.put("productCategoryList", productCategoryList);
			modelMap.put("success", true);
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "empty pageSize or pageIndex or shopId");
		}
		return modelMap;
	}

@RequestMapping(value = "/modifyproduct", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> modifyProduct(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (!VerifyCodeUtil.verifyCode(request)) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "输入了错误的验证码");
			return modelMap;
		}

		Product product = null;
		// 接收前端传递过来的product
		String productStr = null;
		// 商品图片缩略图(输入流和名称的封装类)
		ImageHolder thumbnail = null;

		// 将HttpServletRequest转型为MultipartHttpServletRequest,可以很方便地得到文件名和文件内容
		MultipartHttpServletRequest multipartHttpServletRequest = null;
		// 接收商品缩略图
		CommonsMultipartFile thumbnailFile = null;
		// 接收商品详情图片
		List<ImageHolder> productDetailImgList = new ArrayList<ImageHolder>();

		// 创建一个通用的多部分解析器
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

		// Step2: 使用FastJson提供的api,实例化Product 构造调用service层的第一个参数
		ObjectMapper mapper = new ObjectMapper();
		// 获取前端传递过来的product,约定好使用productStr
		try {
			productStr = HttpServletRequestUtil.getString(request, "productStr");
			product = mapper.readValue(productStr, Product.class);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
			return modelMap;
		}
		// Step3: 商品缩略图 和 商品详情图 构造调用service层的第二个参数和第三个参数
		try {
			// 判断 request 是否有文件上传,即多部分请求
			if (commonsMultipartResolver.isMultipart(request)) {
				// 将request转换成多部分request
				multipartHttpServletRequest = (MultipartHttpServletRequest) request;

				// 得到缩略图的CommonsMultipartFile ,和前端约定好使用thumbnail 传递
				// ,并构建ImageHolder对象
				thumbnailFile = (CommonsMultipartFile) multipartHttpServletRequest.getFile("thumbnail");
				// 转化为ImageHolder,使用service层的参数类型要求
				thumbnail = new ImageHolder(thumbnailFile.getInputStream(), thumbnailFile.getOriginalFilename());

				// 得到 商品详情的列表,和前端约定使用productImg   i 传递 ,并构建ImageHolder对象
				for (int i = 0; i < IMAGEMAXCOUNT; i  ) {
					CommonsMultipartFile productDetailImgFile = (CommonsMultipartFile) multipartHttpServletRequest.getFile("productImg"   i);
					if (productDetailImgFile != null) {
						ImageHolder productDetailImg = new ImageHolder(productDetailImgFile.getInputStream(), productDetailImgFile.getOriginalFilename());
						productDetailImgList.add(productDetailImg);
					} else {
						// 如果从请求中获取的到file为空,终止循环
						break;
					}
				}
			} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "上传图片不能为空");
				return modelMap;
			}
		} catch (Exception e) {
			e.printStackTrace();
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
			return modelMap;
		}

		// Step4 调用Service层
		if (product != null && thumbnailFile != null && productDetailImgList.size() > 0) {
			try {
				// 从session中获取shop信息,不依赖前端的传递更加安全
				Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
				product.setShop(currentShop);
				// 调用addProduct
				ProductExecution pe = productService.modifyProduct(product, thumbnail, productDetailImgList);
				if (pe.getState() == ProductStateEnum.SUCCESS.getState()) {
					modelMap.put("success", true);
				} else {
					modelMap.put("success", false);
					modelMap.put("errMsg", pe.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;
	}
	
	/**
	 * 
	 * 
	 * @Title: changeStatus
	 * 
	 * @Description: 标注@ResponseBody将返回的model解析为json
	 * 
	 * @param request
	 * @return
	 * 
	 * @return: Map
	 */
	@RequestMapping(value = "/changestatus",method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> changeStatus(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		// 获取前端传递过来的product,约定好使用productStr
		try {
			String productStr = HttpServletRequestUtil.getString(request, "productStr");
			Product product = mapper.readValue(productStr, Product.class);
			Shop tempShop = (Shop) request.getSession().getAttribute("currentShop");
			product.setShop(tempShop);

			ProductExecution pe = productService.modifyProduct(product, null, null);
			if (pe.getState() == ProductStateEnum.SUCCESS.getState()) {
				modelMap.put("success", true);
				modelMap.put("errMsg", "操作成功");
			} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", pe.getStateInfo());
			}
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
			return modelMap;
		}
		return modelMap;
	}

单元测试

启动tomcat,我们对getProductById方法进行单元测试。modifyProduct方法待前端开发完成后一并测试。

根据路由规则访问

代码语言:javascript复制
http://localhost:8080/o2o/shopadmin/getproductbyid?productId=7
代码语言:javascript复制
{
    "product": {
        "productId": 7,
        "productName": "offical_product",
        "productDesc": "product offical desc",
        "imgAddr": "\upload\item\shopImage\5\2018070100324625530.jpg",
        "normalPrice": "100",
        "promotionPrice": "80",
        "priority": 66,
        "createTime": 1530286468000,
        "lastEditTime": 1530419566000,
        "enableStatus": 1,
        "productImgList": [
            {
                "productImgId": 14,
                "imgAddr": "\upload\item\shopImage\5\2018070100324625530.jpg",
                "imgDesc": null,
                "priority": 66,
                "createTime": 1530286468000,
                "productId": 7
            },
            {
                "productImgId": 15,
                "imgAddr": "\upload\item\shopImage\5\2018070100324625530.jpg",
                "imgDesc": null,
                "priority": 66,
                "createTime": 1530286468000,
                "productId": 7
            }
        ],
        "productCategory": {
            "productCategoryId": 36,
            "shopId": null,
            "productCategoryName": null,
            "productCategoryDesc": null,
            "priority": null,
            "createTime": null,
            "lastEditTime": null
        },
        "shop": {
            "shopId": 5,
            "shopName": null,
            "shopDesc": null,
            "shopAddr": null,
            "phone": null,
            "shopImg": null,
            "priority": null,
            "createTime": null,
            "lastEditTime": null,
            "enableStatus": null,
            "advice": null,
            "owner": null,
            "area": null,
            "shopCategory": null
        }
    },
    "productCategoryList": [
        {
            "productCategoryId": 36,
            "shopId": 5,
            "productCategoryName": "奶茶",
            "productCategoryDesc": "香飘飘奶茶",
            "priority": 99,
            "createTime": 1529678397000,
            "lastEditTime": 1529678397000
        },
        {
            "productCategoryId": 37,
            "shopId": 5,
            "productCategoryName": "咖啡",
            "productCategoryDesc": "拿铁咖啡",
            "priority": 98,
            "createTime": 1529678397000,
            "lastEditTime": 1529678397000
        }
    ],
    "success": true
}

检查数据是否符合预期。


Github地址

代码地址: https://github.com/yangshangwei/o2o

0 人点赞