提交新商品时直接提示 ”提交失败!“
实在是找不出来错了,修改没问题,就是新增商品直接提示”提交失败!“
这是productoperation.js
$(function() { // 从URL里获取productId参数的值 var productId = getQueryString('productId'); // 通过productId获取商品信息的URL var infoUrl = '/shopadmin/getproductbyid?productId=' + productId; // 获取当前店铺设定的商品类别列表的URL var categoryUrl = '/shopadmin/getproductcategorylist'; // 更新商品信息的URL var productPostUrl = '/shopadmin/modifyproduct'; // 由于商品添加和编辑使用的是同一个页面, // 该标识符用来标明本次是添加还是编辑操作 var isEdit = false; if (productId) { // 若有productId则为编辑操作 getInfo(productId); isEdit = true; } else { getCategory(); productPostUrl = '/shopadmin/addproduct'; } // 获取需要编辑的商品的商品信息,并赋值给表单 function getInfo(id) { $.getJSON( infoUrl, function(data) { if (data.success) { // 从返回的JSON当中获取product对象的信息,并赋值给表单 var product = data.product; $('#product-name').val(product.productName); $('#product-desc').val(product.productDesc); $('#priority').val(product.priority); $('#normal-price').val(product.normalPrice); $('#promotion-price').val( product.promotionPrice); // 获取原本的商品类别以及该店铺的所有商品类别列表 var optionHtml = ''; var optionArr = data.productCategoryList; var optionSelected = product.productCategory.productCategoryId; // 生成前端的HTML商品类别列表,并默认选择编辑前的商品类别 optionArr .map(function(item, index) { var isSelect = optionSelected === item.productCategoryId ? 'selected' : ''; optionHtml += '<option data-value="' + item.productCategoryId + '"' + isSelect + '>' + item.productCategoryName + '</option>'; }); $('#category').html(optionHtml); } }); } // 为商品添加操作提供该店铺下的所有商品类别列表 function getCategory() { $.getJSON(categoryUrl, function(data) { if (data.success) { var productCategoryList = data.data; var optionHtml = ''; productCategoryList.map(function(item, index) { optionHtml += '<option data-value="' + item.productCategoryId + '">' + item.productCategoryName + '</option>'; }); $('#category').html(optionHtml); } }); } // 针对商品详情图控件组,若该控件组的最后一个元素发生变化(即上传了图片), // 且控件总数未达到6个,则生成新的一个文件上传控件 $('.detail-img-div').on('change', '.detail-img:last-child', function() { if ($('.detail-img').length < 6) { $('#detail-img').append('<input type="file" class="detail-img">'); } }); // 提交按钮的事件响应,分别对商品添加和编辑操作做不同响应 $('#submit').click( function() { // 创建商品json对象,并从表单里面获取对应的属性值 var product = {}; product.productName = $('#product-name').val(); product.productDesc = $('#product-desc').val(); product.priority = $('#priority').val(); product.normalPrice = $('#normal-price').val(); product.promotionPrice = $('#promotion-price').val(); // 获取选定的商品类别值 product.productCategory = { productCategoryId : $('#category').find('option').not( function() { return !this.selected; }).data('value') }; product.productId = productId; // 获取缩略图文件流 var thumbnail = $('#small-img')[0].files[0]; // 生成表单对象,用于接收参数并传递给后台 var formData = new FormData(); formData.append('thumbnail', thumbnail); // 遍历商品详情图控件,获取里面的文件流 $('.detail-img').map( function(index, item) { // 判断该控件是否已选择了文件 if ($('.detail-img')[index].files.length > 0) { // 将第i个文件流赋值给key为productImgi的表单键值对里 formData.append('productImg' + index, $('.detail-img')[index].files[0]); } }); // 将product json对象转成字符流保存至表单对象key为productStr的的键值对里 formData.append('productStr', JSON.stringify(product)); // 获取表单里输入的验证码 var verifyCodeActual = $('#j_captcha').val(); if (!verifyCodeActual) { $.toast('请输入验证码!'); return; } formData.append("verifyCodeActual", verifyCodeActual); // 将数据提交至后台处理相关操作 $.ajax({ url : productPostUrl, type : 'POST', data : formData, contentType : false, processData : false, cache : false, success : function(data) { if (data.success) { $.toast('提交成功!'); $('#captcha_img').click(); } else { $.toast('提交失败!'); $('#captcha_img').click(); } } }); }); });
这是productoperation.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>商品编辑</title> <meta name="viewport" content="initial-scale=1, maximum-scale=1"> <link rel="shortcut icon" href="/favicon.ico"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="stylesheet" href="//g.alicdn.com/msui/sm/0.6.2/css/sm.min.css"> <link rel="stylesheet" href="//g.alicdn.com/msui/sm/0.6.2/css/sm-extend.min.css"> <link rel="stylesheet" href="../resources/css/shop/productmanagement.css"> </head> <body> <header class="bar bar-nav"> <h1 class="title">商品编辑</h1> </header> <div class="content"> <div class="list-block"> <ul> <li> <div class="item-content"> <div class="item-media"> <i class="icon icon-form-name"></i> </div> <div class="item-inner"> <div class="item-title label">商品名称</div> <div class="item-input"> <input type="text" id="product-name" placeholder="商品名称"> </div> </div> </div> </li> <li> <div class="item-content"> <div class="item-media"> <i class="icon icon-form-email"></i> </div> <div class="item-inner"> <div class="item-title label">目录</div> <div class="item-input"> <select id="category"> </select> </div> </div> </div> </li> <li> <div class="item-content"> <div class="item-media"> <i class="icon icon-form-email"></i> </div> <div class="item-inner"> <div class="item-title label">优先级</div> <div class="item-input"> <input type="number" id="priority" placeholder="数字越大越排前面"> </div> </div> </div> </li> <!-- TODO 积分--> <!-- <li>--> <!-- <div class="item-content">--> <!-- <div class="item-media">--> <!-- <i class="icon icon-form-email"></i>--> <!-- </div>--> <!-- <div class="item-inner">--> <!-- <div class="item-title label">积分</div>--> <!-- <div class="item-input">--> <!-- <input type="number" id="point" placeholder="商品积分">--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- </li> --> <li> <div class="item-content"> <div class="item-media"> <i class="icon icon-form-email"></i> </div> <div class="item-inner"> <div class="item-title label">原价</div> <div class="item-input"> <input type="number" id="normal-price" placeholder="可选"> </div> </div> </div> </li> <li> <div class="item-content"> <div class="item-media"> <i class="icon icon-form-email"></i> </div> <div class="item-inner"> <div class="item-title label">现价</div> <div class="item-input"> <input type="number" id="promotion-price" placeholder="可选"> </div> </div> </div> </li> <!-- <li> <div class="item-content"> <div class="item-media"> <i class="icon icon-form-email"></i> </div> <div class="item-inner"> <div class="item-title label">积分</div> <div class="item-input"> <input type="number" id="point" placeholder="可选"> </div> </div> </div> </li> --> <li> <div class="item-content"> <div class="item-media"> <i class="icon icon-form-email"></i> </div> <div class="item-inner"> <div class="item-title label">缩略图</div> <div class="item-input"> <input type="file" id="small-img"> </div> </div> </div> </li> <li> <div class="item-content"> <div class="item-media"> <i class="icon icon-form-email"></i> </div> <div class="item-inner detail-img-div"> <div class="item-title label">详情图片</div> <div class="item-input" id="detail-img"> <input type="file" class="detail-img"> <!-- <input type="file" class="detail-img"> <input type="file" class="detail-img"> --> </div> </div> </div> </li> <li> <div class="item-content"> <div class="item-media"> <i class="icon icon-form-email"></i> </div> <div class="item-inner"> <div class="item-title label">商品描述</div> <div class="item-input"> <textarea id="product-desc" placeholder="商品描述"></textarea> </div> </div> </div> </li> <li> <div class="item-content"> <div class="item-media"> <i class="icon icon-form-email"></i> </div> <div class="item-inner"> <label for="j_captcha" class="item-title label">验证码</label> <input id="j_captcha" name="j_captcha" type="text" class="form-control in" placeholder="验证码" /> <div class="item-input"> <img id="captcha_img" alt="点击更换" title="点击更换" onclick="changeVerifyCode(this)" src="../Kaptcha" /> </div> </div> </div> </li> </ul> </div> <div class="content-block"> <div class="row"> <div class="col-50"> <a href="/shopadmin/productmanagement" class="button button-big button-fill button-danger" id="back">返回商品管理</a> </div> <div class="col-50"> <a href="#" class="button button-big button-fill" id="submit">提交</a> </div> </div> </div> </div> <script type='text/javascript' src='//g.alicdn.com/sj/lib/zepto/zepto.min.js' charset='utf-8'></script> <script type='text/javascript' src='//g.alicdn.com/msui/sm/0.6.2/js/sm.min.js' charset='utf-8'></script> <script type='text/javascript' src='//g.alicdn.com/msui/sm/0.6.2/js/sm-extend.min.js' charset='utf-8'></script> <script type='text/javascript' src='../resources/js/common/common.js' charset='utf-8'></script> <script type='text/javascript' src='../resources/js/shop/productoperation.js' charset='utf-8'></script> <!-- 解决 Formart is not a function --> <script src="//github.com/jacwright/date.format.git"></script> </body> </html>
这是ProductManagementController
package com.shop.o2o.web.shopadmin; import com.fasterxml.jackson.databind.ObjectMapper; import com.shop.o2o.dto.ImageHolder; import com.shop.o2o.dto.ProductExecution; import com.shop.o2o.entity.Product; import com.shop.o2o.entity.ProductCategory; import com.shop.o2o.entity.Shop; import com.shop.o2o.enums.ProductStateEnum; import com.shop.o2o.exceptions.ProductOperationException; import com.shop.o2o.service.ProductCategoryService; import com.shop.o2o.service.ProductService; import com.shop.o2o.util.CodeUtil; import com.shop.o2o.util.HttpServletRequestUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/shopadmin") public class ProductManagementController { @Autowired private ProductService productService; @Autowired private ProductCategoryService productCategoryService; //支持上传商品详情图的最大数量 private static final int IMAGEMAXCOUNT = 6; @PostMapping("/addproduct") @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; ImageHolder thumbnail = null; List<ImageHolder> productImgList = new ArrayList<ImageHolder>(); CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext());//从request获取文件流 try { // 若请求中存在文件流,则取出相关的文件(包括缩略图和详情图) if (multipartResolver.isMultipart(request)) { 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 { 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; } // 若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 (ProductOperationException e) { modelMap.put("success", false); modelMap.put("errMsg", e.toString()); return modelMap; } } else { modelMap.put("success", false); modelMap.put("errMsg", "请输入商品信息"); } 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>列表对象,最多支持六张图片上传 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; } /** * 通过商品id获取商品信息 * @param productId * @return */ @GetMapping("/getproductbyid") @ResponseBody private Map<String, Object> getProductById(@RequestParam Long productId) {//接收从前端传来的productId Map<String, Object> modelMap = new HashMap<String, Object>(); // 非空判断 if (productId > -1) { // 获取商品信息 Product product = productService.getProductById(productId); // 获取该店铺下的商品类别列表 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; } @PostMapping("/modifyproduct") @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("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; } /** * 通过店铺id获取该店铺下的商品列表 * @param request * @return */ @GetMapping("/getproductlistbyshop") @ResponseBody private Map<String, Object> getProductListByShop(HttpServletRequest request) { Map<String, Object> modelMap = new HashMap<String, Object>(); // 获取前台传过来的页码 int pageIndex = HttpServletRequestUtil.getInt(request, "pageIndex"); // 获取前台传过来的每页要求返回的商品数上限 int pageSize = HttpServletRequestUtil.getInt(request, "pageSize"); // 从当前session中获取店铺信息,主要是获取shopId Shop currentShop = (Shop) request.getSession().getAttribute("currentShop"); // 空值判断 if ((pageIndex > -1) && (pageSize > -1) && (currentShop != null) && (currentShop.getShopId() != null)) { // 获取传入的需要检索的条件,包括是否需要从某个商品类别以及模糊查找商品名去筛选某个店铺下的商品列表 // 筛选的条件可以进行排列组合 long productCategoryId = HttpServletRequestUtil.getLong(request, "productCategoryId"); String productName = HttpServletRequestUtil.getString(request, "productName"); Product productCondition = compactProductCondition(currentShop.getShopId(), productCategoryId, productName); // 传入查询条件以及分页信息进行查询,返回相应商品列表以及总数 ProductExecution pe = productService.getProductList(productCondition, pageIndex, pageSize); modelMap.put("productList", pe.getProductList()); modelMap.put("count", pe.getCount()); modelMap.put("success", true); } else { modelMap.put("success", false); modelMap.put("errMsg", "empty pageSize or pageIndex or shopId"); } return modelMap; } /** * 封装商品查询条件到Product实例中 * @param shopId(mandatory) * @param productCategoryId(optional) * @param productName(optional) * @return */ private Product compactProductCondition(long shopId, long productCategoryId, String productName) { Product productCondition = new Product(); Shop shop = new Shop(); shop.setShopId(shopId); productCondition.setShop(shop); // 若有指定类别的要求则添加进去 if (productCategoryId != -1L) { ProductCategory productCategory = new ProductCategory(); productCategory.setProductCategoryId(productCategoryId); productCondition.setProductCategory(productCategory); } // 若有商品名模糊查询的要求则添加进去 if (productName != null) { productCondition.setProductName(productName); } return productCondition; } }
26
收起
正在回答
7回答
同学你好,对比同学的html和js代码,没有太大问题,只是在productPostUrl前少了项目名,问一下同学使用IDEA,在application context处是没有加项目名是吗?
建议同学查看一下添加商品是productPostUrl是什么?ajax执行时,productPostUrl是否有值。
祝:学习愉快~
qq_森林中的小熊_0
2019-11-27 17:56:04
老师看到的话回复一下吧,谢谢了,想一天了,productoperation.js是直接复制的源码,还没有配置redis相关的内容,加了后面视频里讲的拦截器,不知道是不是这些原因
qq_森林中的小熊_0
2019-11-27 17:34:18
qq_森林中的小熊_0
2019-11-27 17:33:44
qq_森林中的小熊_0
2019-11-27 17:31:47
好像ajax没有向后端传数据直接就结束了
qq_森林中的小熊_0
2019-11-27 17:17:18
4. SSM到Spring Boot入门与综合实战
- 参与学习 人
- 提交作业 323 份
- 解答问题 8263 个
本阶段将带你学习主流框架SSM,以及SpringBoot ,打通成为Java工程师的最后一公里!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星