实战SSM_O2O商铺_13【商铺注册】View层之初始化页面数据

文章目录

  • 请求过程分析
  • DAO层的实现
    • AreaDao接口,Mapper映射文件及单元测试
    • ShopCategoryDao接口
    • ShopCategoryDao.xml Mapper映射文件
    • 单元测试
  • Service层的实现
    • AreaService接口,AreaServiceImpl接口实现类及单元测试
    • ShopCategoryService接口
    • ShopCategoryServiceImpl 接口实现类
    • 单元测试
  • Controller层
  • 部署调测
  • Github地址

实战SSM_O2O商铺_13【商铺注册】View层之初始化页面数据_第1张图片

请求过程分析

页面画完之后,我们的下拉框是没有数据的

					<!-- 商铺分类  下拉列表 -->
						<li>
							<div class="item-content">
								<div class="item-inner">
									<div class="item-title label">商铺分类</div>
									<div class="item-input">
										<!-- 增加id,便于js中操作,需要从后台读取数据 -->
										<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="shop-area">
										</select>
									</div>
								</div>
							</div>
						</li>

在初始换页面加载js的时候调用

// 调用函数,加载数据
getShopInitInfo();

函数定义如下:

/**
	 * 从后台加载获取下拉菜单的值
	 */
	function getShopInitInfo() {
		$.getJSON(initUrl, function(data) {
			if (data.success) {
				var tempShopCategoryHtml = '';
				var tempShopAreaHtml = '';
				data.shopCategoryList.map(function(item, index) {
					tempShopCategoryHtml += ' item.shopCategoryId + '">' + item.shopCategoryName
							+ '';
				});

				data.areaList.map(function(item, index) {
					tempShopAreaHtml += ' item.areaId
							+ '">' + item.areaName + '';
				});
				// 获取html中对应标签的id 赋值
				$('#shop-category').html(tempShopCategoryHtml);
				$('#shop-area').html(tempShopAreaHtml)

			}else{
				$.toast(data.errMsg);
			}
		});
	};

请求 initUrl , 我们设置的值为/o2o/shopadmin/getshopinitinfo ,根据web.xml中配置拦截所有请求可知在经过DispatcherServlet分发到Controller层,接收到请求后继续处理。


DAO层的实现

需要获取商铺分类列表和区域列表,DAO层我们还没做完,来完善下

实战SSM_O2O商铺_13【商铺注册】View层之初始化页面数据_第2张图片


AreaDao接口,Mapper映射文件及单元测试

我们在实战SSM_O2O商铺_05集成SSM后验证DAO层、Service层、Controller层的配置中已经开发了queryArea接口以及配置了mapper映射文件,我们这里直接复用这个接口即可。


剩下的就是ShopCategory的了。

ShopCategoryDao接口

/o2o/src/main/java/com/artisan/o2o/dao/ShopCategoryDao.java

package com.artisan.o2o.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.artisan.o2o.entity.ShopCategory;

public interface ShopCategoryDao {
	/**
	 * 
	 * 
	 * @Title: queryShopCategoryList
	 * 
	 * @Description: 按照需求
	 * 
	 *               1.首页展示一级目录(即parent_id 为 null的商铺类别)
	 * 
	 *               2.点进去某个一级目录加载对应目录下的子目录
	 * 
	 *               所以这里需要加个入参ShopCategory,并通过MyBatis提供的注解@Param与Mapper映射文件中的SQL关联起来
	 *               ,在SQL中进行判断
	 * 
	 * @return
	 * 
	 * @return: List
	 */
	List<ShopCategory> queryShopCategoryList(@Param("shopCategoryCondition") ShopCategory shopCategory);

}


ShopCategoryDao.xml Mapper映射文件

/o2o/src/main/resources/mapper/ShopCategoryDao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.artisan.o2o.dao.ShopCategoryDao">
	<select id="queryShopCategoryList" resultType="com.artisan.o2o.entity.ShopCategory">
		SELECT
			shop_category_id ,
			shop_category_name,
			shop_category_desc,
			shop_category_img,
			priority,
			create_time,
			last_edit_time,
			parent_id
		FROM
			tb_shop_category
	<where>
		<!-- 控制层getshopinitinfo的方法 shopCategoryService.getShopCategoryList(new ShopCategory());
			只能选择二级商铺类别,不能挂载一级商铺类别大类目录下
		 -->
		<if test="shopCategoryCondition != null">
			and parent_id is not null
		</if>
		<!-- 如果传递了父类的id,则查询对应父类下的目录 -->
		<if test="shopCategoryCondition.parent != null">
			and parent_id = #{shopCategoryCondition.parent.shopCategoryId}
		</if>
	</where>	
		ORDER BY priority 
		DESC	
	</select>
</mapper>   
 
 
    
     

单元测试

tb_shop_category中的数据

为了方便测试,我们添加几条测试数据

-- ----------------------------
-- Records of tb_shop_category
-- ----------------------------
INSERT INTO `tb_shop_category` VALUES ('1', '咖啡奶茶', '咖啡奶茶大类', '/xxxx/xxxx', '0', '2018-05-18 02:13:56', '2018-05-18 02:13:58', null);
INSERT INTO `tb_shop_category` VALUES ('2', '咖啡', '咖啡小类', '/yyyy/yyyy', '2', '2018-05-18 03:38:17', '2018-05-18 03:38:20', '1');
INSERT INTO `tb_shop_category` VALUES ('3', '奶茶', '奶茶小类', '/aaa/bbb', '0', '2018-05-29 14:36:55', '2018-05-29 14:36:58', '1');

单元测试类

package com.artisan.o2o.dao;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.artisan.o2o.BaseTest;
import com.artisan.o2o.entity.ShopCategory;

public class ShopCategoryDaoTest extends BaseTest {
	

	@Autowired
	ShopCategoryDao shopCategoryDao;
	
	@Test
	public void testQueryShopCategoryList() {

		// shopCategoryCondition 不为null的情况,查询parent_id is not null 的数据
		ShopCategory shopCategory = new ShopCategory();
		List<ShopCategory> categoryList = shopCategoryDao.queryShopCategoryList(shopCategory);
		Assert.assertEquals(2, categoryList.size());
		for (ShopCategory shopCategory2 : categoryList) {
			System.out.println(shopCategory2);
		}

		// shopCategoryCondition.parent 不为null的情况

		// 查询parent=1的店铺目录
		ShopCategory child = new ShopCategory();
		ShopCategory parent = new ShopCategory();
		parent.setShopCategoryId(1L);
		child.setParent(parent);

		categoryList = shopCategoryDao.queryShopCategoryList(child);
		Assert.assertEquals(2, categoryList.size());
		for (ShopCategory shopCategory2 : categoryList) {
			System.out.println(shopCategory2);
		}

	}


}

检查日志信息是否符合预期

五月 29, 2018 2:44:57 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 2, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 10000, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1br1ebw9v1c27wf2172af4p|74f0ea28, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1br1ebw9v1c27wf2172af4p|74f0ea28, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/o2o?useUnicode=true&characterEncoding=utf8, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 30, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 10, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@38234a38] will not be managed by Spring
==>  Preparing: SELECT shop_category_id , shop_category_name, shop_category_desc, shop_category_img, priority, create_time, last_edit_time, parent_id FROM tb_shop_category WHERE parent_id is not null ORDER BY priority DESC 
==> Parameters: 
<==    Columns: shop_category_id, shop_category_name, shop_category_desc, shop_category_img, priority, create_time, last_edit_time, parent_id
<==        Row: 2, 咖啡, 咖啡小类, /yyyy/yyyy, 2, 2018-05-18 03:38:17.0, 2018-05-18 03:38:20.0, 1
<==        Row: 3, 奶茶, 奶茶小类, /aaa/bbb, 0, 2018-05-29 14:36:55.0, 2018-05-29 14:36:58.0, 1
<==      Total: 2
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@36cda2c2]
ShopCategory [shopCategoryId=2, shopCategoryName=咖啡, shopCategoryDesc=咖啡小类, shopCategoryImg=/yyyy/yyyy, priority=2, createTime=Fri May 18 03:38:17 BOT 2018, lastEditTime=Fri May 18 03:38:20 BOT 2018, parent=null]
ShopCategory [shopCategoryId=3, shopCategoryName=奶茶, shopCategoryDesc=奶茶小类, shopCategoryImg=/aaa/bbb, priority=0, createTime=Tue May 29 14:36:55 BOT 2018, lastEditTime=Tue May 29 14:36:58 BOT 2018, parent=null]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@29ca3d04] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@52c3cb31] will not be managed by Spring
==>  Preparing: SELECT shop_category_id , shop_category_name, shop_category_desc, shop_category_img, priority, create_time, last_edit_time, parent_id FROM tb_shop_category WHERE parent_id is not null and parent_id = ? ORDER BY priority DESC 
==> Parameters: 1(Long)
<==    Columns: shop_category_id, shop_category_name, shop_category_desc, shop_category_img, priority, create_time, last_edit_time, parent_id
<==        Row: 2, 咖啡, 咖啡小类, /yyyy/yyyy, 2, 2018-05-18 03:38:17.0, 2018-05-18 03:38:20.0, 1
<==        Row: 3, 奶茶, 奶茶小类, /aaa/bbb, 0, 2018-05-29 14:36:55.0, 2018-05-29 14:36:58.0, 1
<==      Total: 2
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@29ca3d04]
ShopCategory [shopCategoryId=2, shopCategoryName=咖啡, shopCategoryDesc=咖啡小类, shopCategoryImg=/yyyy/yyyy, priority=2, createTime=Fri May 18 03:38:17 BOT 2018, lastEditTime=Fri May 18 03:38:20 BOT 2018, parent=null]
ShopCategory [shopCategoryId=3, shopCategoryName=奶茶, shopCategoryDesc=奶茶小类, shopCategoryImg=/aaa/bbb, priority=0, createTime=Tue May 29 14:36:55 BOT 2018, lastEditTime=Tue May 29 14:36:58 BOT 2018, parent=null]
五月 29, 2018 2:44:58 下午 org.springframework.context.support.GenericApplicationContext doClose
信息: Closing org.springframework.context.support.GenericApplicationContext@ae45eb6: startup date [Tue May 29 14:44:53 BOT 2018]; root of context hierarchy

单元测试通过


Service层的实现

实战SSM_O2O商铺_13【商铺注册】View层之初始化页面数据_第3张图片


AreaService接口,AreaServiceImpl接口实现类及单元测试

我们在实战SSM_O2O商铺_05集成SSM后验证DAO层、Service层、Controller层的配置中已经开发了AreaService接口,AreaServiceImpl接口实现类及单元测试,我们这里直接复用即可。


ShopCategoryService接口

/o2o/src/main/java/com/artisan/o2o/service/ShopCategoryService.java

package com.artisan.o2o.service;

import java.util.List;

import com.artisan.o2o.entity.ShopCategory;

public interface ShopCategoryService {

	List<ShopCategory> getShopCategoryList(ShopCategory shopCategory);
}


ShopCategoryServiceImpl 接口实现类

/o2o/src/main/java/com/artisan/o2o/service/impl/ShopCategoryServiceImpl.java

package com.artisan.o2o.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.artisan.o2o.dao.ShopCategoryDao;
import com.artisan.o2o.entity.ShopCategory;
import com.artisan.o2o.service.ShopCategoryService;


@Service
public class ShopCategoryServiceImpl implements ShopCategoryService {
	
	@Autowired
	private ShopCategoryDao shopCategoryDao;
	
	@Override
	public List<ShopCategory> getShopCategoryList(ShopCategory shopCategory) {
		return shopCategoryDao.queryShopCategoryList(shopCategory);
	}

}

单元测试

package com.artisan.o2o.service;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.artisan.o2o.BaseTest;
import com.artisan.o2o.entity.ShopCategory;

public class ShopServiceCategoryTest extends BaseTest {

	@Autowired
	ShopCategoryService shopCategoryService;

	@Test
	public void testQueryShopCategory() {
		ShopCategory shopCategory = new ShopCategory();
		List<ShopCategory> shopCategories = shopCategoryService.getShopCategoryList(shopCategory);
		Assert.assertEquals(2, shopCategories.size());
		for (ShopCategory shopCategory2 : shopCategories) {
			System.out.println(shopCategory2);
		}
	}
}

验证符合预期,单元测试OK。


Controller层

实战SSM_O2O商铺_13【商铺注册】View层之初始化页面数据_第4张图片

前端js中的请求路径

// 获取基本信息的URL
var initUrl = '/o2o/shopadmin/getshopinitinfo';

/o2o/src/main/java/com/artisan/o2o/web/shopadmin/ShopController.java#getshopinitinfo 中使用@RequestMapping匹配前端请求的URL,返回前端的数据为@ResponseBody将返回Map类型转为的JSON串

/**
	 * 
	 * 
	 * @Title: getshopinitinfo
	 * 
	 * @Description: 初始化区域信息 和 ShopCategory信息,返回给前台表单页面
	 * 
	 * @return: Map
	 */
	@RequestMapping(value = "/getshopinitinfo", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getshopinitinfo() {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		List<ShopCategory> shopCategoryList = null;
		List<Area> areaList = null;
		try {
			shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory());
			areaList = areaservice.getAreaList();
			// 返回success shopCategoryList  areaList,前端通过 data.success来判断从而展示shopCategoryList和areaList的数据
			modelMap.put("success", true);
			modelMap.put("shopCategoryList", shopCategoryList);
			modelMap.put("areaList", areaList);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
		}
		return modelMap;
	}
	

当然了别忘了注入

	@Autowired
	private ShopCategoryService shopCategoryService;

	@Autowired
	private AreaService areaservice;


部署调测

启动tomcat ,调测阶段可以通过debug的方式,更加详细了解请求过程。

实战SSM_O2O商铺_13【商铺注册】View层之初始化页面数据_第5张图片

可以看到已经加载了后端的数据,并且符合需求。 店铺分类加载二级目录,区域加载全部区域.


Github地址

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

你可能感兴趣的:(【实战-SSM,In,Action】,实战系列-SSM实战)