老师你好,这是补充的 ProductManagementController 中的将 currentShop 设置到 product 的代码:
以及这是完整的 controller 中的modifyProduct 代码:
@RequestMapping(value = "/modifyproduct", method = RequestMethod.POST)
@ResponseBody
private Map<String, Object> modifyProduct(HttpServletRequest request) {
Map<String, Object> modelMap = new HashMap<>();
// 判断何时调用,商品编辑时 or 上下架操作时调用
// 如果为前者,进行验证码判断;如果是后者则跳过验证码判断
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<>();
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("errMag", 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("errMag", e.toString());
return modelMap;
}
// 非空判断,确保 Product 实体类不为空,就可以更新了;图片流是否传入无所谓
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("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;
}