无法获取数据库商铺分类和区域信息
老师,在跟随项目的学习过程中,本节介绍了店铺分类的标准和区域信息的获取。这里用shopoperation.html页面来做测试,我已经实现在数据库里添加了数据。进行测试的时候没有报错,但是数据库里的商铺分类并没有显示在页面上,这是为什么?
另外,做项目的时候,我发现用项目的C3P0数据库,在我这边无法连接上,启动都会报错,所以我自己换成了spring自带的数据库池,这样就可以正常访问数据库了,之前跟做的几个测试也顺利测试成功。这是什么原因啊?难道C3P0还认编译器?我用IDEA跟做项目,视频中用的是eclipse
我的相关代码基本是复制项目源码上稍加修改而来,对源代码几乎没有污染,如下
ShopAdminController.java:
package com.lgq.o2o.web.shopadmin; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping(value = "shopadmin", method = { RequestMethod.GET }) /** * 主要用来解析路由并转发到相应的html中 * * @author xiangze * */ public class ShopAdminController { @RequestMapping(value = "/shopoperation") public String shopOperation() { // 转发至店铺注册/编辑页面 return "shop/shopoperation"; } @RequestMapping(value = "/shoplist") public String shopList() { // 转发至店铺列表页面 return "shop/shoplist"; } @RequestMapping(value = "/shopmanagement") public String shopManagement() { // 转发至店铺管理页面 return "shop/shopmanagement"; } @RequestMapping(value = "/productcategorymanagement", method = RequestMethod.GET) private String productCategoryManage() { // 转发至商品类别管理页面 return "shop/productcategorymanagement"; } @RequestMapping(value = "/productoperation") public String productOperation() { // 转发至商品添加/编辑页面 return "shop/productoperation"; } @RequestMapping(value = "/productmanagement") public String productManagement() { // 转发至商品管理页面 return "shop/productmanagement"; } }
ShopManagementContorller.java:
package com.lgq.o2o.web.shopadmin; import com.fasterxml.jackson.databind.ObjectMapper; import com.lgq.o2o.dto.ImageHolder; import com.lgq.o2o.dto.ProductCategoryExecution; import com.lgq.o2o.dto.ShopExecution; import com.lgq.o2o.entity.Area; import com.lgq.o2o.entity.PersonInfo; import com.lgq.o2o.entity.Shop; import com.lgq.o2o.entity.ShopCategory; import com.lgq.o2o.enums.ProductCategoryStateEnum; import com.lgq.o2o.enums.ShopStateEnum; import com.lgq.o2o.exceptions.ProductCategoryOperationException; import com.lgq.o2o.exceptions.ShopOperationException; import com.lgq.o2o.service.AreaService; import com.lgq.o2o.service.ProductCategoryService; import com.lgq.o2o.service.ShopCategoryService; import com.lgq.o2o.service.ShopService; import com.lgq.o2o.util.CodeUtil; import com.lgq.o2o.util.HttpServletRequestUtil; 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 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 ShopManagementContorller { @Autowired private ShopService shopService; @Autowired private ShopCategoryService shopCategoryService; @Autowired private AreaService areaService; @Autowired private ProductCategoryService productCategoryService; @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 = new PersonInfo(); // user.setUserId(1L); // user.setName("test"); // request.getSession().setAttribute("user", user); //TODO PersonInfo user = (PersonInfo) request.getSession().getAttribute("user"); try { Shop shopCondition = new Shop(); shopCondition.setOwner(user); ShopExecution se = shopService.getShopList(shopCondition, 0, 100); request.getSession().setAttribute("shopList", se.getShopList()); modelMap.put("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();//这个mapper用来做转换 Shop shop = null; try { shop = mapper.readValue(shopStr, Shop.class); } catch (Exception e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); return modelMap; } /*接收图片,这里用spring自带的CommonsMultipartFile,同时需要CommonsMultipartResolver这个 解析器,去解析request里面的文件信息。从CommonsMultipartResolver可知,它要从本次会话当中的上下 文去获取相关文件上传的内容*/ CommonsMultipartFile shopImg = null; CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); //用commonsMultipartResolver判断请求中是否有上传的文件流,如果有文件流,就将request做一下转换 //转换成MultipartHttpServletRequest类对象 if (commonsMultipartResolver.isMultipart(request)) { MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");//“shopImg”是前段约定好的名 } else { modelMap.put("success", false); modelMap.put("errMsg", "上传图片不能为空"); return modelMap; } // 2.注册店铺 if (shop != null && shopImg != null) { PersonInfo owner = (PersonInfo) request.getSession().getAttribute("user");//店主信息通过会话来获取 owner.setUserId(1L); shop.setOwner(owner); ShopExecution se = null; 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; } } @RequestMapping(value = "/removeproductcategory", method = RequestMethod.POST) @ResponseBody private Map<String, Object> removeProductCategory(Long productCategoryId, HttpServletRequest request) { Map<String, Object> modelMap = new HashMap<String, Object>(); if (productCategoryId != null && productCategoryId > 0) { try { Shop currentShop = (Shop) request.getSession().getAttribute("currentShop"); ProductCategoryExecution pe = productCategoryService.deleteProductCategory(productCategoryId, currentShop.getShopId()); if (pe.getState() == ProductCategoryStateEnum.SUCCESS.getState()) { modelMap.put("success", true); } else { modelMap.put("success", false); modelMap.put("errMsg", pe.getStateInfo()); } } catch (ProductCategoryOperationException e) { modelMap.put("success", false); modelMap.put("errMsg", e.toString()); return modelMap; } } else { modelMap.put("success", false); modelMap.put("errMsg", "请至少选择一个商品类别"); } return modelMap; } }
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> <!-- 验证码 kaptcha --> <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> <!-- 解决 Formart is not a function --> <script src="//github.com/jacwright/date.format.git"></script> </body> </html>
spring-dao.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" 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"> <!-- 配置整合mybatis过程 --> <!-- 1.配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/> <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/> <!-- <bean class="com.lgq.o2o.util.EncryptPropertyPlaceholderConfigurer">--> <!-- <property name="locations">--> <!-- <list>--> <!-- <value>classpath:jdbc.properties</value>--> <!-- <value>classpath:redis.properties</value>--> <!-- </list>--> <!-- </property>--> <!-- <property name="fileEncoding" value="UTF-8" />--> <!-- </bean>--> <!-- 2.数据库连接池 --> <!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">--> <!-- <!–配置连接池属性–>--> <!-- <property name="driverClass" value="${jdbc.driver}"/>--> <!-- <property name="jdbcUrl" value="${jdbc.url}"/>--> <!-- <property name="user" value="${jdbc.username}"/>--> <!-- <property name="password" value="${jdbc.password}"/>--> <!-- <!– c3p0连接池的私有属性 –>--> <!-- <property name="maxPoolSize" value="40" />--> <!-- <property name="minPoolSize" value="10" />--> <!-- <!– 关闭连接后不自动commit –>--> <!-- <property name="autoCommitOnClose" value="false" />--> <!-- <!– 获取连接超时时间 –>--> <!-- <property name="checkoutTimeout" value="10000" />--> <!-- <!– 当获取连接失败重试次数 –>--> <!-- <property name="acquireRetryAttempts" value="2" />--> <!-- </bean>--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 3.配置SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 配置MyBaties全局配置文件:mybatis-config.xml --> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- 扫描entity包 使用别名 --> <property name="typeAliasesPackage" value="com.lgq.o2o.entity" /> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml" /> </bean> <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="com.lgq.o2o.dao" /> </bean> </beans>
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.lgq.o2o.web" /> <!-- 5.权限拦截器 --> <mvc:interceptors> <!-- 校验是否已登录了店家管理系统的拦截器 --> <!-- <mvc:interceptor>--> <!-- <mvc:mapping path="/shopadmin/**" />--> <!-- <bean id="ShopInterceptor"--> <!-- class="com.lgq.o2o.interceptor.shopadmin.ShopLoginInterceptor" />--> <!-- </mvc:interceptor>--> <!-- 校验是否对该店铺有操作权限的拦截器 --> <mvc:interceptor> <mvc:mapping path="/shopadmin/**" /> <!-- shoplist page --> <mvc:exclude-mapping path="/shopadmin/shoplist" /> <mvc:exclude-mapping path="/shopadmin/getshoplist" /> <!-- shopregister page --> <mvc:exclude-mapping path="/shopadmin/getshopinitinfo" /> <mvc:exclude-mapping path="/shopadmin/registershop" /> <mvc:exclude-mapping path="/shopadmin/shopoperation" /> <!-- shopmanage page --> <mvc:exclude-mapping path="/shopadmin/shopmanagement" /> <mvc:exclude-mapping path="/shopadmin/getshopmanagementinfo" /> <bean id="ShopPermissionInterceptor" class="com.lgq.o2o.interceptor.shopadmin.ShopPermissionInterceptor" /> </mvc:interceptor> </mvc:interceptors> </beans>
数据库表:
访问页面效果:
正在回答 回答被采纳积分+1
老师,都试过了,我删掉整个项目,重新复制过来配置本地参数,然后按照您说的方法重新clean,项目还是正常能跑,总感觉项目在访问数据方面老是存在问题,整个项目运行起来有些不稳定。
有时启动项目可以访问商铺信息了,有时又不能。
有时点击某个店铺管理页面里的“商铺信息”按钮,有时候访问的URL是。。。。。。/shopadmin/shopmanagement?shopId=xxx,
有时候又会是/shopadmin/shopmanagement,就是有时带shopId有时不带那种,但是代码不变,按钮是同一个。而且有时访问可以显示店铺分类和地域,有时无法显示空白
另外就是,尝试增加或修改店铺信息发现输入验证码正确的情况下有时会报“提交失败,请填入商铺信息”,但这个时候我是填写了店铺简介的。甚至有时候直接报无法提交
更有情况,直接输入账号密码,点击登陆时候,一个白页,即访问不了shoplist页面
做以上测试的时候,代码完全没有改动,这是什么现象啊?我感觉不是代码问题了
同学你好!
没有打印出来可能是由于,缓存的问题导致的,建议同学clean一下项目,重新启动测试一下
商品详情这里加载可能会慢一些,同学可以查看页面的上面是否还在转圈来判断是否加载完了
关于图片,同学需要自己配置一下呢,可以参考源码中的教辅第三点后面进行配置:(截图不全注意仔细查看教辅)
注意:配置好后,启动项目时一定要启动redis,否则不能够查看图片。
Dao层配置mybatis时已经进行过配置了,所以这里不需要写注解也是可以的。同学的不可以可能是由于没有编译好的原因。有时加载项目较慢,同学需要耐心等待一下
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
老师,eclipse找不出原因,我尝试在控制器添加输出语句来验证,但控制台没有输出,这次我源码文件全部搞到idea环境下,除了包名和一些本地属性,其他源码都没改,然后根据本地测试教辅资料进行设置。但是启动tomcat居然会报错说redis出现了问题,我在想之前数据读取不了跟这个有没关系,具体报错情况如下:
尝试访问
控制台报错:
2019-10-10 10:10:30.346 [http-nio-8080-exec-10] INFO org.springframework.web.servlet.DispatcherServlet - Initializing Servlet 'spring-dispatcher' 2019-10-10 10:10:30.511 [http-nio-8080-exec-10] WARN o.s.web.context.support.XmlWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jedisPoolConfig' defined in file [D:\compiling_software\idea\software\workspace\o2o\target\o2o\WEB-INF\classes\spring\spring-redis.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'maxTotal'; nested exception is java.lang.NumberFormatException: For input string: "${redis.pool.maxActive}" 2019-10-10 10:10:30.511 [http-nio-8080-exec-10] ERROR org.springframework.web.servlet.DispatcherServlet - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jedisPoolConfig' defined in file [D:\compiling_software\idea\software\workspace\o2o\target\o2o\WEB-INF\classes\spring\spring-redis.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'maxTotal'; nested exception is java.lang.NumberFormatException: For input string: "${redis.pool.maxActive}" at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:701) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:667) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:715) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:590) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:529) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:169) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1122) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1077) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:761) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1747) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'maxTotal'; nested exception is java.lang.NumberFormatException: For input string: "${redis.pool.maxActive}" at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:595) at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:604) at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:219) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1730) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1686) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1433) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) ... 35 common frames omitted Caused by: java.lang.NumberFormatException: For input string: "${redis.pool.maxActive}" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:569) at java.lang.Integer.valueOf(Integer.java:766) at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:211) at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:115) at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:429) at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:402) at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:155) at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:585) ... 41 common frames omitted
同学你好。
1、前台报错的原因是,这里的script外部文件没有加type='text/javascript':
2、c3p0的错误可能是由于版本不匹配造成的,可以试试替换为下面的依赖:
<dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency>
3、至于页面无法获取下拉列表的问题,请同学先停下Tomcat,清除浏览器缓存Ctrl+Shift+Delete,重新编译后再试
祝学习愉快~
老师,确实有报错,但是我看了下这个ajax请求路径,好像没错呀。
另外,关于C3P0使用的,我分别用两种数据库配置做了下AreaDaoTest.java里的testQueryArea方法,相关代码和结果如下:
AreaDaoTest.java:
package com.lgq.o2o.dao; import com.lgq.o2o.BaseTest; import com.lgq.o2o.entity.Area; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import static org.junit.Assert.assertEquals; public class AreaDaoTest extends BaseTest { @Autowired private AreaDao areaDao; @Test public void testQueryArea(){ //测试areaDao的queryArea()方法 List<Area> areaList = areaDao.queryArea(); //System.out.println(areaList); // //如果areaList集合元素数目是2的话,则测试成功 assertEquals(2, areaList.size()); } }
用spring自带数据库连接池:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean>
控制台输出结果(运行成功的):
用C3P0连接池(教学项目中用的那种):
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!--配置连接池属性--> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- c3p0连接池的私有属性 --> <property name="maxPoolSize" value="40" /> <property name="minPoolSize" value="10" /> <!-- 关闭连接后不自动commit --> <property name="autoCommitOnClose" value="false" /> <!-- 获取连接超时时间 --> <property name="checkoutTimeout" value="10000" /> <!-- 当获取连接失败重试次数 --> <property name="acquireRetryAttempts" value="2" /> </bean>
控制台输出结果:
- 参与学习 人
- 提交作业 323 份
- 解答问题 8263 个
本阶段将带你学习主流框架SSM,以及SpringBoot ,打通成为Java工程师的最后一公里!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星