采纳答案成功!
向帮助你的同学说点啥吧!感谢那些助人为乐的人
Tomcat可以正常启动,但是就是不能进入DEBUG模式是为什么
老师还有一个问题
@RequestMapping(value = "/getshopinitinfo", method = RequestMethod.GET) @ResponseBody private Map<String, Object> getShopInitInfo() { Map<String, Object> modelMap = new HashMap<String, Object>(); List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>(); List<Area> areaList = new ArrayList<Area>(); try { shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory()); areaList = areaService.getAreaList(); modelMap.put("shopCategoryList", shopCategoryList); modelMap.put("areaList", areaList); modelMap.put("success", true); } catch (Exception e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); } return modelMap; }
上面这段代码实在执行shopoperation.js 的getShopInitInfo函数时触发
是向http://localhost:8080/o2o/shopadmin/getshopinitinfo发送了一个GET请求吗?
老师会不会是这一条警告影响的呢?
9月 02, 2018 1:41:26 下午 com.mchange.v2.c3p0.C3P0Registry banner 信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10] WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.apache.ibatis.reflection.Reflector (file:/H:/tomcat/webapps/myapp/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/o2o/WEB-INF/lib/mybatis-3.4.2.jar) to method java.lang.Object.finalize() WARNING: Please consider reporting this to the maintainers of org.apache.ibatis.reflection.Reflector WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release
我仍然获取不了前台提交的数据
这个跟Java艰难没有关系,同学坚持下来会发现其实和php差不多,唯一区别就在于每次都得重启服务器才能看到结果:),目前感觉问题应该出在 $.ajax({ url : registerShopUrl, type : 'POST', data : formData, contentType : false, processData : false, cache : false, success : function(data) { if (data.success) { $.toast('提交成功'); } else { $.toast('提交失败' + data.errMsg); } $('#captcha_img').click(); } }) 这个地方, 同学可以试着把js里添加img的这段给注释掉了,逐步排查一下,同时记得重启tomcat clean tomcat然后清除浏览器缓存。其实遇到问题去解决才达到教学的目的,工作中往往一个困难会被困扰很久都解决不了,所以提前锻炼下才有效果,一帆风顺的学习根本就不能成长:)
package com.imooc.o2o.web.shopadmin; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import com.fasterxml.jackson.databind.ObjectMapper; import com.imooc.o2o.dto.ImageHolder; import com.imooc.o2o.dto.ShopExecution; import com.imooc.o2o.entity.Area; import com.imooc.o2o.entity.PersonInfo; import com.imooc.o2o.entity.Shop; import com.imooc.o2o.entity.ShopCategory; import com.imooc.o2o.enums.ShopStateEnum; import com.imooc.o2o.exceptions.ShopOperationException; import com.imooc.o2o.service.AreaService; import com.imooc.o2o.service.ShopCategoryService; import com.imooc.o2o.service.ShopService; import com.imooc.o2o.util.CodeUtil; import com.imooc.o2o.util.HttpServletRequestUtil; @Controller @RequestMapping("/shopadmin") public class ShopManagementController { @Autowired private ShopService shopService; @Autowired private ShopCategoryService shopCategoryService; @Autowired private AreaService areaService; @RequestMapping(value = "/getshopmanagementinfo", method = RequestMethod.GET) @ResponseBody private Map<String, Object> getShopManagementInfo(HttpServletRequest request) { Map<String, Object> modelMap = new HashMap<String, Object>(); long shopId = HttpServletRequestUtil.getLong(request, "shopId"); if (shopId <= 0) { Object currentShopObj = request.getSession().getAttribute("currentShop"); if (currentShopObj == null) { modelMap.put("redirect", true); modelMap.put("url", "/o2o/shopadmin/shoplist"); } else { Shop currentShop = (Shop) currentShopObj; modelMap.put("redirect", false); modelMap.put("shopId", currentShop.getShopId()); } } else { Shop currentShop = new Shop(); currentShop.setShopId(shopId); request.getSession().setAttribute("currentShop", currentShop); modelMap.put("redirect", false); } return modelMap; } @RequestMapping(value = "/getshoplist", method = RequestMethod.GET) @ResponseBody private Map<String, Object> getShopList(HttpServletRequest request) { Map<String, Object> modelMap = new HashMap<String, Object>(); PersonInfo user = (PersonInfo) request.getSession().getAttribute("user"); try { Shop shopCondition = new Shop(); shopCondition.setOwner(user); ShopExecution se = shopService.getShopList(shopCondition, 0, 100); modelMap.put("shopList", se.getShopList()); // 列出店铺成功之后,将店铺放入session中作为权限验证依据,即该帐号只能操作它自己的店铺 request.getSession().setAttribute("shopList", se.getShopList()); modelMap.put("user", user); modelMap.put("success", true); } catch (Exception e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); } return modelMap; } @RequestMapping(value = "/getshopbyid", method = RequestMethod.GET) @ResponseBody private Map<String, Object> getShopById(HttpServletRequest request) { Map<String, Object> modelMap = new HashMap<String, Object>(); Long shopId = HttpServletRequestUtil.getLong(request, "shopId"); if (shopId > -1) { try { Shop shop = shopService.getByShopId(shopId); List<Area> areaList = areaService.getAreaList(); modelMap.put("shop", shop); modelMap.put("areaList", areaList); modelMap.put("success", true); } catch (Exception e) { modelMap.put("success", false); modelMap.put("errMsg", e.toString()); } } else { modelMap.put("success", false); modelMap.put("errMsg", "empty shopId"); } return modelMap; } @RequestMapping(value = "/getshopinitinfo", method = RequestMethod.GET) @ResponseBody private Map<String, Object> getShopInitInfo() { Map<String, Object> modelMap = new HashMap<String, Object>(); List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>(); List<Area> areaList = new ArrayList<Area>(); try { shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory()); areaList = areaService.getAreaList(); modelMap.put("shopCategoryList", shopCategoryList); modelMap.put("areaList", areaList); modelMap.put("success", true); } catch (Exception e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); } return modelMap; } @RequestMapping(value = "/registershop", method = RequestMethod.POST) @ResponseBody private Map<String, Object> registerShop(HttpServletRequest request) { Map<String, Object> modelMap = new HashMap<String, Object>(); if (!CodeUtil.checkVerifyCode(request)) { modelMap.put("success", false); modelMap.put("errMsg", "输入了错误的验证码"); return modelMap; } // 1.接收并转化相应的参数,包括店铺信息以及图片信息 String shopStr = HttpServletRequestUtil.getString(request, "shopStr"); ObjectMapper mapper = new ObjectMapper(); Shop shop = null; try { shop = mapper.readValue(shopStr, Shop.class); } catch (Exception e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); return modelMap; } CommonsMultipartFile shopImg = null; CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); if (commonsMultipartResolver.isMultipart(request)) { MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg"); } else { modelMap.put("success", false); modelMap.put("errMsg", "上传图片不能为空"); return modelMap; } // 2.注册店铺 if (shop != null && shopImg != null) { PersonInfo owner = (PersonInfo) request.getSession().getAttribute("user"); shop.setOwner(owner); ShopExecution se; try { ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(), shopImg.getInputStream()); se = shopService.addShop(shop, imageHolder); if (se.getState() == ShopStateEnum.CHECK.getState()) { modelMap.put("success", true); // 该用户可以操作的店铺列表 @SuppressWarnings("unchecked") List<Shop> shopList = (List<Shop>) request.getSession().getAttribute("shopList"); if (shopList == null || shopList.size() == 0) { shopList = new ArrayList<Shop>(); } shopList.add(se.getShop()); request.getSession().setAttribute("shopList", shopList); } else { modelMap.put("success", false); modelMap.put("errMsg", se.getStateInfo()); } } catch (ShopOperationException e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); } catch (IOException e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); } return modelMap; } else { modelMap.put("success", false); modelMap.put("errMsg", "请输入店铺信息"); return modelMap; } } @RequestMapping(value = "/modifyshop", method = RequestMethod.POST) @ResponseBody private Map<String, Object> modifyShop(HttpServletRequest request) { Map<String, Object> modelMap = new HashMap<String, Object>(); if (!CodeUtil.checkVerifyCode(request)) { modelMap.put("success", false); modelMap.put("errMsg", "输入了错误的验证码"); return modelMap; } // 1.接收并转化相应的参数,包括店铺信息以及图片信息 String shopStr = HttpServletRequestUtil.getString(request, "shopStr"); ObjectMapper mapper = new ObjectMapper(); Shop shop = null; try { shop = mapper.readValue(shopStr, Shop.class); } catch (Exception e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); return modelMap; } CommonsMultipartFile shopImg = null; CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); if (commonsMultipartResolver.isMultipart(request)) { MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg"); } // 2.修改店铺信息 if (shop != null && shop.getShopId() != null) { ShopExecution se; try { if (shopImg == null) { se = shopService.modifyShop(shop, null); } else { ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(), shopImg.getInputStream()); se = shopService.modifyShop(shop, imageHolder); } if (se.getState() == ShopStateEnum.SUCCESS.getState()) { modelMap.put("success", true); } else { modelMap.put("success", false); modelMap.put("errMsg", se.getStateInfo()); } } catch (ShopOperationException e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); } catch (IOException e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); } return modelMap; } else { modelMap.put("success", false); modelMap.put("errMsg", "请输入店铺Id"); return modelMap; } } }
肯定是哪里配置有问题了,同学可以直接把我的复制粘贴直接复用看看哈,记得清除内存 然后试试
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1" metadata-complete="true"> <display-name>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>aaa.jsp</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> <!-- 是否有边框 --> <init-param> <param-name>kaptcha.border</param-name> <param-value>no</param-value> </init-param> <!-- 字体颜色 --> <init-param> <param-name>kaptcha.textproducer.font.color</param-name> <param-value>red</param-value> </init-param> <!-- 图片宽度 --> <init-param> <param-name>kaptcha.image.width</param-name> <param-value>135</param-value> </init-param> <!-- 使用哪些字符生成验证码 --> <init-param> <param-name>kaptcha.textproducer.char.string</param-name> <param-value>ACDEFHKPRSTWX345679</param-value> </init-param> <!-- 图片高度 --> <init-param> <param-name>kaptcha.image.height</param-name> <param-value>50</param-value> </init-param> <!-- 字体大小 --> <init-param> <param-name>kaptcha.textproducer.font.size</param-name> <param-value>43</param-value> </init-param> <!-- 干扰线的颜色 --> <init-param> <param-name>kaptcha.noise.color</param-name> <param-value>black</param-value> </init-param> <!-- 字符个数 --> <init-param> <param-name>kaptcha.textproducer.char.length</param-name> <param-value>4</param-value> </init-param> <!-- 字体 --> <init-param> <param-name>kaptcha.textproducer.font.names</param-name> <param-value>Arial</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Kaptcha</servlet-name> <url-pattern>/Kaptcha</url-pattern> </servlet-mapping> <servlet> <servlet-name>spring-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>spring-dispatcher</servlet-name> <!-- 默认匹配所有的请求 --> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
spring-web.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 配置SpringMVC --> <!-- 1.开启SpringMVC注解模式 --> <!-- 简化配置: (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持 --> <mvc:annotation-driven /> <!-- 2.静态资源默认servlet配置 (1)加入对静态资源的处理:js,gif,png (2)允许使用"/"做整体映射 --> <mvc:resources mapping="/resources/**" location="/resources/" /> <mvc:default-servlet-handler /> <!-- 3.定义视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/html/"></property> <property name="suffix" value=".html"></property> </bean> <!-- 文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <property name="maxUploadSize" value="10485760000"></property><!-- 最大上传文件大小 --> <property name="maxInMemorySize" value="10960"></property> </bean> <!-- 在spring-mvc.xml文件中加入这段配置后,spring返回给页面的都是utf-8编码了 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <!-- 4.扫描web相关的bean --> <context:component-scan base-package="com.imooc.myo2o.web" /> </beans>
shopoperation.js
/** * */ $(function() { // 从URL里获取shopId参数的值 var shopId = getQueryString('shopId'); // 由于店铺注册和编辑使用的是同一个页面, // 该标识符用来标明本次是添加还是编辑操作 var isEdit = shopId ? true : false; // 用于店铺注册时候的店铺类别以及区域列表的初始化的URL var initUrl = '/o2o/shopadmin/getshopinitinfo'; // 注册店铺的URL var registerShopUrl = '/o2o/shopadmin/registershop'; // 编辑店铺前需要获取店铺信息,这里为获取当前店铺信息的URL var shopInfoUrl = "/o2o/shopadmin/getshopbyid?shopId=" + shopId; // 编辑店铺信息的URL var editShopUrl = '/o2o/shopadmin/modifyshop'; // 判断是编辑操作还是注册操作 if (!isEdit) { getShopInitInfo(); } else { getShopInfo(shopId); } // 通过店铺Id获取店铺信息 function getShopInfo(shopId) { $.getJSON(shopInfoUrl, function(data) { if (data.success) { // 若访问成功,则依据后台传递过来的店铺信息为表单元素赋值 var shop = data.shop; $('#shop-name').val(shop.shopName); $('#shop-addr').val(shop.shopAddr); $('#shop-phone').val(shop.phone); $('#shop-desc').val(shop.shopDesc); // 给店铺类别选定原先的店铺类别值 var shopCategory = '<option data-id="' + shop.shopCategory.shopCategoryId + '" selected>' + shop.shopCategory.shopCategoryName + '</option>'; var tempAreaHtml = ''; // 初始化区域列表 data.areaList.map(function(item, index) { tempAreaHtml += '<option data-id="' + item.areaId + '">' + item.areaName + '</option>'; }); $('#shop-category').html(shopCategory); // 不允许选择店铺类别 $('#shop-category').attr('disabled', 'disabled'); $('#area').html(tempAreaHtml); // 给店铺选定原先的所属的区域 $("#area option[data-id='" + shop.area.areaId + "']").attr( "selected", "selected"); } }); } // 取得所有二级店铺类别以及区域信息,并分别赋值进类别列表以及区域列表 function getShopInitInfo() { $.getJSON(initUrl, function(data) { if (data.success) { var tempHtml = ''; var tempAreaHtml = ''; data.shopCategoryList.map(function(item, index) { tempHtml += '<option data-id="' + item.shopCategoryId + '">' + item.shopCategoryName + '</option>'; }); data.areaList.map(function(item, index) { tempAreaHtml += '<option data-id="' + item.areaId + '">' + item.areaName + '</option>'; }); $('#shop-category').html(tempHtml); $('#area').html(tempAreaHtml); } }); } // 提交按钮的事件响应,分别对店铺注册和编辑操作做不同响应 $('#submit').click(function() { // 创建shop对象 var shop = {}; if (isEdit) { // 若属于编辑,则给shopId赋值 shop.shopId = shopId; } // 获取表单里的数据并填充进对应的店铺属性中 shop.shopName = $('#shop-name').val(); shop.shopAddr = $('#shop-addr').val(); shop.phone = $('#shop-phone').val(); shop.shopDesc = $('#shop-desc').val(); // 选择选定好的店铺类别 shop.shopCategory = { shopCategoryId : $('#shop-category').find('option').not(function() { return !this.selected; }).data('id') }; // 选择选定好的区域信息 shop.area = { areaId : $('#area').find('option').not(function() { return !this.selected; }).data('id') }; // 获取上传的图片文件流 var shopImg = $('#shop-img')[0].files[0]; // 生成表单对象,用于接收参数并传递给后台 var formData = new FormData(); // 添加图片流进表单对象里 formData.append('shopImg', shopImg); // 将shop json对象转成字符流保存至表单对象key为shopStr的的键值对里 formData.append('shopStr', JSON.stringify(shop)); // 获取表单里输入的验证码 var verifyCodeActual = $('#j_captcha').val(); if (!verifyCodeActual) { $.toast('请输入验证码!'); return; } formData.append('verifyCodeActual', verifyCodeActual); // 将数据提交至后台处理相关操作 $.ajax({ url : (isEdit ? editShopUrl : registerShopUrl), type : 'POST', data : formData, contentType : false, processData : false, cache : false, success : function(data) { if (data.success) { $.toast('提交成功!'); if (!isEdit) { // 若为注册操作,成功后返回店铺列表页 window.location.href = "/o2o/shopadmin/shoplist"; } } else { $.toast('提交失败!' + data.errMsg); } // 点击验证码图片的时候,注册码会改变 $('#captcha_img').click(); } }); }); })
shopoperation.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>SUI Mobile Demo</title> <meta name="description" content="MSUI: Build mobile apps with simple HTML, CSS, and JS components."> <meta name="author" content="阿里巴巴国际UED前端"> <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"> <meta name="format-detection" content="telephone=no"> <!-- Google Web Fonts --> <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="apple-touch-icon-precomposed" href="/assets/img/apple-touch-icon-114x114.png"> </head> <body> <div class="page-group"> <div id="page-label-input" class="page"> <header class="bar bar-nav"> <a class="button button-link button-nav pull-left back" href="/demos/form"> <span class="icon icon-left"></span> 返回 </a> <h1 class="title">商店信息</h1> </header> <div class="content"> <div class="list-block"> <ul> <!-- Text inputs --> <li> <div class="item-content"> <div class="item-inner"> <div class="item-title label">商铺名称</div> <div class="item-input"> <input type="text" id="shop-name" placeholder="商铺名称"> </div> </div> </div> </li> <!-- 商铺分类 下拉列表 --> <li> <div class="item-content"> <div class="item-inner"> <div class="item-title label">商铺分类</div> <div class="item-input"> <select id="shop-category"> </select> </div> </div> </div> </li> <!-- 区域分类 下拉列表 --> <li> <div class="item-content"> <div class="item-inner"> <div class="item-title label">所属区域</div> <div class="item-input"> <select id="area"> </select> </div> </div> </div> </li> <!-- 详细地址 text --> <li> <div class="item-content"> <div class="item-inner"> <div class="item-title label">详细地址</div> <div class="item-input"> <input type="text" id="shop-addr" placeholder="详细地址"> </div> </div> </div> </li> <!-- 联系电话 text --> <li> <div class="item-content"> <div class="item-inner"> <div class="item-title label">联系电话</div> <div class="item-input"> <input type="text" id="shop-phone" placeholder="联系电话"> </div> </div> </div> </li> <!-- 缩略图 上传控件 --> <li> <div class="item-content"> <div class="item-inner"> <div class="item-title label">缩略图</div> <div class="item-input"> <input type="file" id="shop-img"> </div> </div> </div> </li> <!-- 店铺简介 textarea --> <li class="align-top"> <div class="item-content"> <div class="item-inner"> <div class="item-title label">店铺简介</div> <div class="item-input"> <textarea id="shop-desc" placeholder="店铺简介"></textarea> </div> </div> </div> </li> <!-- 验证码 ka --> <li> <div class="item-content"> <div class="item-inner"> <div class="item-title label">验证码</div> <input type="text" id="j_captcha" 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="/o2o/shopadmin/shopmanagement" class="button button-big button-fill button-danger">返回</a> </div> <div class="col-50"> <a href="#" class="button button-big button-fill button-success" id="submit">提交</a> </div> </div> </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/shopoperation.js' charset='utf-8'></script> </body> </html>
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1" metadata-complete="true"> <display-name>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>aaa.jsp</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> <!-- 是否有边框 --> <init-param> <param-name>kaptcha.border</param-name> <param-value>no</param-value> </init-param> <!-- 字体颜色 --> <init-param> <param-name>kaptcha.textproducer.font.color</param-name> <param-value>red</param-value> </init-param> <!-- 图片宽度 --> <init-param> <param-name>kaptcha.image.width</param-name> <param-value>135</param-value> </init-param> <!-- 使用哪些字符生成验证码 --> <init-param> <param-name>kaptcha.textproducer.char.string</param-name> <param-value>ACDEFHKPRSTWX345679</param-value> </init-param> <!-- 图片高度 --> <init-param> <param-name>kaptcha.image.height</param-name> <param-value>50</param-value> </init-param> <!-- 字体大小 --> <init-param> <param-name>kaptcha.textproducer.font.size</param-name> <param-value>43</param-value> </init-param> <!-- 干扰线的颜色 --> <init-param> <param-name>kaptcha.noise.color</param-name> <param-value>black</param-value> </init-param> <!-- 字符个数 --> <init-param> <param-name>kaptcha.textproducer.char.length</param-name> <param-value>4</param-value> </init-param> <!-- 字体 --> <init-param> <param-name>kaptcha.textproducer.font.names</param-name> <param-value>Arial</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Kaptcha</servlet-name> <url-pattern>/Kaptcha</url-pattern> </servlet-mapping> <servlet> <servlet-name>spring-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>spring-dispatcher</servlet-name> <!-- 默认匹配所有的请求 --> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
CodeUtil.java
package com.imooc.o2o.util; import org.apache.catalina.servlet4preview.http.HttpServletRequest; public class CodeUtil { public static boolean checkVerifyCode(HttpServletRequest request) { String verifyCodeExpected=(String)request.getSession().getAttribute( com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); String verifyCodeActual=HttpServletRequestUtil.getString(request, "verifyCodeActual"); if(verifyCodeActual==null||!verifyCodeActual.equals(verifyCodeExpected)) { return false; } return true; } }
shopoperation
$(function() { var initUrl = '/o2o/shopadmin/getshopinitinfo'; var registerShopUrl = '/o2o/shopadmin/registershop'; getShopInitInfo(); function getShopInitInfo() { $.getJSON(initUrl, function(data) { if (data.success) { var tempHtml = ''; var tempAreaHtml = ''; data.shopCategoryList.map(function(item, index) { tempHtml += '<option data-id="' + item.shopCategoryId + '">' + item.shopCategoryName + '</option>'; }); data.areaList.map(function(item, index) { tempAreaHtml += '<option data-id="' + item.shopareaId + '">' + item.areaName + '</option>'; }); $('#shop-category').html(tempHtml); $('#area').html(tempAreaHtml); } }); $('#submit').click( function() { var shop = {}; shop.shopName = $('#shop-name').val(); shop.shopAddr = $('#shop-addr').val(); shop.phone = $('#shop-phone').val(); shop.shopDesc = $('#shop-desc').val(); shop.shopCategory = { shopCategoryId : $('#shop-category').find('option').not( function() { return !this.selected; }).data('id') }; shop.area = { areaId : $('#area').find('option').not(function() { return !this.selected; }).data('id') }; var shopImg = $('#shop-img')[0].files[0]; var formData = new FormData(); formData.append('shopImg', shopImg); formData.append('shopStr', JSON.stringify(shop)); var verifyCodeActual=$('#j_captcha').val(); if(!verifyCodeActual){ $.toast('请输入验证码!'); return; } formData.append('verifyCodeActual',verifyCodeActual); $.ajax({ url : registerShopUrl, type : 'POST', data : formData, contentType : false, processData : false, cache : false, success : function(data) { if (data.success) { $.toast('提交成功'); } else { $.toast('提交失败' + data.errMsg); } $('#captcha_img').click(); } }) }); } })
ShopManagementController.java
package com.imooc.o2o.web.shopadmin; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.catalina.servlet4preview.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import com.fasterxml.jackson.databind.ObjectMapper; import com.imooc.o2o.dto.ShopExecution; import com.imooc.o2o.entity.Area; import com.imooc.o2o.entity.PersonInfo; import com.imooc.o2o.entity.Shop; import com.imooc.o2o.entity.ShopCategory; import com.imooc.o2o.enums.ShopStateEnum; import com.imooc.o2o.exceptions.ShopOperationException; import com.imooc.o2o.service.AreaService; import com.imooc.o2o.service.ShopCategoryService; import com.imooc.o2o.service.ShopService; import com.imooc.o2o.util.CodeUtil; import com.imooc.o2o.util.HttpServletRequestUtil; @Controller @RequestMapping("/shopadmin") public class ShopManagementController { @Autowired private ShopService shopService; @Autowired private ShopCategoryService shopCategoryService; @Autowired private AreaService areaService; @RequestMapping(value = "/getshopinitinfo", method = RequestMethod.GET) @ResponseBody private Map<String, Object> getShopInitInfo() { Map<String, Object> modelMap = new HashMap<String, Object>(); List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>(); List<Area> areaList = new ArrayList<Area>(); try { shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory()); areaList = areaService.getAreaList(); modelMap.put("shopCategoryList", shopCategoryList); modelMap.put("areaList", areaList); modelMap.put("success", true); } catch (Exception e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); } return modelMap; } @RequestMapping(value = "/registershop", method = RequestMethod.POST) @ResponseBody private Map<String, Object> registerShop(HttpServletRequest request) { Map<String, Object> modelMap = new HashMap<String, Object>(); if (!CodeUtil.checkVerifyCode(request)) { modelMap.put("success", false); modelMap.put("errMsg", "输入了错误的验证码"); return modelMap; } // 1.接收并转化相应的参数,包括店铺信息以及图片信息 String shopStr = HttpServletRequestUtil.getString(request, "shopStr"); ObjectMapper mapper = new ObjectMapper(); Shop shop = null; try { shop = mapper.readValue(shopStr, Shop.class); } catch (Exception e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); return modelMap; } CommonsMultipartFile shopImg = null; CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); if (commonsMultipartResolver.isMultipart(request)) { MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg"); } else { modelMap.put("success", false); modelMap.put("errMsg", "上传图片不能为null"); return modelMap; } // 2.注册店铺 if (shop != null && shopImg != null) { PersonInfo owner = new PersonInfo(); owner.setUserId(1L); shop.setOwner(owner); ShopExecution se; try { se = shopService.addShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename()); if (se.getState() == ShopStateEnum.CHECK.getState()) { modelMap.put("success", true); } else { modelMap.put("success", false); modelMap.put("errMsg", se.getStateInfo()); } } catch (ShopOperationException e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); } catch (IOException e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); } return modelMap; } else { modelMap.put("success", false); modelMap.put("errMsg", "请输入店铺信息"); return modelMap; } // 3.返回结果 } // private static void inputStreamToFile(InputStream ins, File file) { // FileOutputStream os = null; // try { // os = new FileOutputStream(file); // int bytesRead = 0; // byte[] buffer = new byte[1024]; // while (((bytesRead = ins.read(buffer))) != -1) { // os.write(buffer, 0, bytesRead); // } // } catch (Exception e) { // throw new RuntimeException("调用inputStreamToFile产生异常" + e.getMessage()); // } finally { // try { // if (os != null) { // os.close(); // } // if (ins != null) { // ins.close(); // } // } catch (Exception e) { // throw new RuntimeException("inputStreamToFile关闭io产生异常" + e.getMessage()); // } // } // }// }
spring-web.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 配置SpringMVC --> <!-- 1.开启SpringMVC注解模式 --> <mvc:annotation-driven /> <!-- 2.静态资源默认servlet配置 (1)加入对静态资源的处理:js,gif,png (2)允许使用"/"做整体映射 --> <mvc:resources mapping="/resources/**" location="/resources/" /> <mvc:default-servlet-handler /> <!-- 3.定义视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/html/"></property> <property name="suffix" value=".html"></property> </bean> <!-- 文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <!-- 1024 * 1024 * 20 = 20M --> <property name="maxUploadSize" value="20971520"></property> <property name="maxInMemorySize" value="20971520"></property> </bean> <!-- 4.扫描web相关的bean --> <context:component-scan base-package="com.imooc.o2o.web" /> </beans>
老师,我基本都是照着视频敲的,所以这代码应该和老师你视频里的一致,但是现在有两个问题,第一个是:一开始调试的时候,后台获取生成图片的验证码是正确的,但是后来调试验证码变成错误的了,好像是获取了下次生成的新验证码,第二个是:通过HttpServletRequestUtil.getString获取的所有信息都是NULL,获取shopImg还有verifyCodeActual也是NULL。
登录后可查看更多问答,登录/注册
SSM商铺V1.0,解决毕设痛点;SpringBoot商铺V2.0,满足工作刚需
了解课程