【Java实战】SSM到SpringBoot校园商铺全栈开发第7章:商品类别模块

12 篇文章 1 订阅
10 篇文章 2 订阅

 7-1 第一次家庭作业:商品类别列表展示

 7-2 公布答案:商品类别列表展示从后到前

Dao层:添加queryProductCategoryList

/**
 * 通过shop id查询店铺所有商品类别
 * @param shopId
 * @return
 */
List<ProductCategory> queryProductCategoryList(long shopId);

Mapper层:

<select id="queryProductCategoryList" resultType="com.doit.o2o.entity.ProductCategory" parameterType="Long">
		SELECT product_category_id,product_category_name,priority,create_time,shop_id
		FROM tb_product_category
		WHERE shop_id=#{shopId}
		ORDER BY priority DESC
</select>

Service层:

接口:

List<ProductCategory> getProductCategoryList(long shopId);

实现: 

@Override
public List<ProductCategory> getProductCategoryList(long shopId) {
	return productCategoryDao.queryProductCategoryList(shopId);
}

Controller层:

@RequestMapping(value="/getproductcategorylist",method=RequestMethod.GET)
	@ResponseBody
	private Result<List<ProductCategory>> getProductCategoryList(HttpServletRequest request){
		
//		Shop shop = new Shop();
//		shop.setShopId(1L);
//		request.getSession().setAttribute("currentShop", shop);
		
		//从店铺管理页面进入,getShopManagementInfo方法已在session中设置了currentShop的值
		Shop currentShop = (Shop)request.getSession().getAttribute("currentShop");
		
		List<ProductCategory> list = null;
		if(currentShop!=null&&currentShop.getShopId()>0){
			list = productCategoryService.getProductCategoryList(currentShop.getShopId());
			return new Result<List<ProductCategory>>(true,list);
		}else{
			ProductCategoryStateEnum ps = ProductCategoryStateEnum.INNER_ERROR;
			return new Result<List<ProductCategory>>(false,ps.getState(),ps.getStateInfo());
		}
	}

 7-3 商品类别批量添加后端开发

Dao层:

/**
 * 批量新增商品类别
 * @param productCategoryList
 * @return
 */
int batchInsertProductCategory(List<ProductCategory> productCategoryList);

Mapper层:

<insert id="batchInsertProductCategory" parameterType="java.util.List">
		INSERT INTO tb_product_category(product_category_name,priority,create_time,shop_id)
		VALUES
		<foreach collection="list" item="productCategory" index="index" separator=",">
		(
		#{productCategory.productCategoryName},
		#{productCategory.priority},
		#{productCategory.createTime},
		#{productCategory.shopId}
		)
		</foreach>
</insert>

Service层:

ProductCategoryExecution batchAddProductCategoryList(List<ProductCategory> productCategoryList);
@Override
	@Transactional
	public ProductCategoryExecution batchAddProductCategoryList(List<ProductCategory> productCategoryList) {
		if(productCategoryList!=null&&productCategoryList.size()>0){
			try {
				int effectedNum = productCategoryDao
						.batchInsertProductCategory(productCategoryList);
				if (effectedNum <= 0) {
					throw new RuntimeException("店铺类别失败");
				} else {

					return new ProductCategoryExecution(
							ProductCategoryStateEnum.SUCCESS);
				}

			} catch (Exception e) {
				throw new RuntimeException("batchAddProductCategory error: "
						+ e.getMessage());
			}
		}else{
			return new ProductCategoryExecution(ProductCategoryStateEnum.EMPTY_LIST);
		}
	}

 Controller层:

@RequestMapping(value = "/addproductcategories", method = RequestMethod.POST)
	@ResponseBody
	private Map<String,Object> addProductCategories(@RequestBody List<ProductCategory> productCategoryList
			,HttpServletRequest request){
		Map<String,Object> modelMap = new HashMap<String,Object>();
		Shop currentShop = (Shop)request.getSession().getAttribute("currentShop");
		long currentShopId = currentShop.getShopId();
		for(ProductCategory productCategory:productCategoryList){
			productCategory.setShopId(currentShopId);
		}
		if(productCategoryList!=null&&productCategoryList.size()>0){
			try{
				ProductCategoryExecution pe = productCategoryService.batchAddProductCategoryList(productCategoryList);
				if(pe.getState()==ProductCategoryStateEnum.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;
	}

 7-4 商品类别批量添加的前端开发

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/productcategorymanagement.css">
    </head>
<body>
    <header class="bar bar-nav">
        <h1 class="title">商品分类管理</h1>
    </header>
    <div class="content">
        <div class="content-block">
            <div class="row row-product-category">
                <div class="col-33">类别</div>
                <div class="col-33">优先级</div>
                <div class="col-33">操作</div>
            </div>
            <div class="category-wrap">
    
            </div>
        </div>
        <div class="content-block">
            <div class="row">
                <div class="col-50">
                    <a href="#" class="button button-big button-fill button-success" id="new">新增</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/productcategorymanagement.js' charset='utf-8'></script>
</body>
</html>

js:

$(function() {
	
	var listUrl = '/o2o/shopadmin/getproductcategorylist';
	var addUrl = '/o2o/shopadmin/addproductcategories';
	var deleteUrl = '/o2o/shopadmin/removeproductcategory';

	$
			.getJSON(
					listUrl,
					function(data) {
						if (data.success) {
							var dataList = data.data;
							$('.category-wrap').html('');
							var tempHtml = '';
							dataList
									.map(function(item, index) {
										tempHtml += ''
												+ '<div class="row row-product-category now">'
												+ '<div class="col-33 product-category-name">'
												+ item.productCategoryName
												+ '</div>'
												+ '<div class="col-33">'
												+ item.priority
												+ '</div>'
												+ '<div class="col-33"><a href="#" class="button delete" data-id="'
												+ item.productCategoryId
												+ '">删除</a></div>' + '</div>';
									});
							$('.category-wrap').append(tempHtml);
						}
					});

	function getList() {
		$
				.getJSON(
						listUrl,
						function(data) {
							if (data.success) {
								var dataList = data.data;
								$('.category-wrap').html('');
								var tempHtml = '';
								dataList
										.map(function(item, index) {
											tempHtml += ''
													+ '<div class="row row-product-category now">'
													+ '<div class="col-33 product-category-name">'
													+ item.productCategoryName
													+ '</div>'
													+ '<div class="col-33">'
													+ item.priority
													+ '</div>'
													+ '<div class="col-33"><a href="#" class="button delete" data-id="'
													+ item.productCategoryId
													+ '">删除</a></div>'
													+ '</div>';
										});
								$('.category-wrap').append(tempHtml);
							}
						});
	}
	getList();

	$('#submit').click(function() {
		var tempArr = $('.temp');
		var productCategoryList = [];
		tempArr.map(function(index, item) {
			var tempObj = {};
			tempObj.productCategoryName = $(item).find('.category').val();
			tempObj.priority = $(item).find('.priority').val();
			if (tempObj.productCategoryName && tempObj.priority) {
				productCategoryList.push(tempObj);
			}
		});
		$.ajax({
			url : addUrl,
			type : 'POST',
			data : JSON.stringify(productCategoryList),
			contentType : 'application/json',
			success : function(data) {
				if (data.success) {
					$.toast('提交成功!');
					getList();
				} else {
					$.toast('提交失败!');
				}
			}
		});
	});

	$('#new')
			.click(
					function() {
						var tempHtml = '<div class="row row-product-category temp">'
								+ '<div class="col-33"><input class="category-input category" type="text" placeholder="分类名"></div>'
								+ '<div class="col-33"><input class="category-input priority" type="number" placeholder="优先级"></div>'
								+ '<div class="col-33"><a href="#" class="button delete">删除</a></div>'
								+ '</div>';
						$('.category-wrap').append(tempHtml);
					});

	$('.category-wrap').on('click', '.row-product-category.now .delete',
			function(e) {
				var target = e.currentTarget;
				$.confirm('确定嘛?', function() {
					$.ajax({
						url : deleteUrl,
						type : 'POST',
						data : {
							productCategoryId : target.dataset.id
						},
						dataType : 'json',
						success : function(data) {
							if (data.success) {
								$.toast('删除成功!');
								getList();
							} else {
								$.toast('删除失败!');
							}
						}
					});
				});
			});

	$('.category-wrap').on('click', '.row-product-category.temp .delete',
			function(e) {
				console.log($(this).parent().parent());
				$(this).parent().parent().remove();

			});
});

 css:

.row-product-category {
    border: 1px solid #999;
    padding: .5rem;
    border-bottom: none;
}
.row-product-category:last-child {
    border-bottom: 1px solid #999;
}
.category-input {
    border: none;
    background-color: #eee;
}
.product-category-name {
    white-space: nowrap;
    overflow-x: scroll;
}

 7-5 商品类别删除后端开发

Dao层:

/**
 * 删除商品类别(初版,即只支持删除尚且没有发布商品的商品类别)
 * @param productCategoryId
 * @param shopId
 * @return
 */
int deleteProductCategory(@Param("productCategoryId") long productCategoryId,@Param("shopId") long shopId);

Mapper层:

<delete id="deleteProductCategory">
		<!-- 具体的sql -->
		DELETE FROM tb_product_category
		WHERE product_category_id = #{productCategoryId}
		AND shop_id=#{shopId}
</delete>

 Service层:

/**
 * 将此类别下的商品的类别id置为空,再删除掉该商品类别
 * @param productCategoryId
 * @param shopId
 * @return
*/
ProductCategoryExecution deleteProductCategory(long productCategoryId,long shopId);
@Override
	@Transactional
	public ProductCategoryExecution deleteProductCategory(long productCategoryId, long shopId) 
		throws ProductCategoryOperationException{
		//TODO将此商品类别下的商品的类别Id置为空
		try{
			int effectedNum = productCategoryDao.deleteProductCategory(productCategoryId, shopId);
			if(effectedNum<=0){
				throw new RuntimeException("商品类别删除失败");
			}else{
				return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
			}
		}catch(Exception e){
			throw new RuntimeException("deleteProductCategory error: "
					+ e.getMessage());
		}
	}

 Controller层:

@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");
				long currentShopId = currentShop.getShopId();
				ProductCategoryExecution pe = productCategoryService.deleteProductCategory(productCategoryId, currentShopId);
				if(pe.getState()==ProductCategoryStateEnum.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;
	}

 7-6 商品类别删除前端开发

同7-4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值