第四天-商品规格的实现

1 商品描述

1.1 数据库

商品表、商品描述表。

分开的目的是为了提高查询效率。

1.2 Dao层

把商品描述信息保存到tb_item_desc表中。

可以使用逆向工程生成的代码

1.3 Mapper文件

逆向工程生成的mapper可以使用

1.4 Service层

接收商品描述调用dao把商品描述插入到表中。

参数:String 商品描述

返回值:TaotaoResult

ItemService.java

在【taotao-manager-service】项目下,【src/main/java】目录下【com.taotao.service】包,【ItemService.java】文件

package com.taotao.service;

import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbItem;

public interface ItemService {

//	查询商品
	TbItem getItemById(long itemId);
	
//	分页
	EUDataGridResult  getItemList(int page,int rows);
	
//	商品添加功能实现
//	商品信息、添加商品描述
	TaotaoResult createItem(TbItem item, String desc 
	) throws Exception;
}

ItemServiceImpl.java

在【taotao-manager-service】项目下,【src/main/java】目录下【com.taotao.service.impl】包,【ItemServiceImpl.java】文件

package com.taotao.service.impl;

import java.util.Date;
import java.util.List;

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

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.IDUtils;
import com.taotao.mapper.TbItemDescMapper;
import com.taotao.mapper.TbItemMapper;
import com.taotao.mapper.TbItemParamItemMapper;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemDesc;
import com.taotao.pojo.TbItemExample;
import com.taotao.pojo.TbItemExample.Criteria;
import com.taotao.pojo.TbItemParamItem;
import com.taotao.service.ItemService;

/**
 * 商品管理Service
 * <p>Title: ItemServiceImpl</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.com</p> 
 * @author	入云龙
 * @date	2015年9月2日上午10:47:14
 * @version 1.0
 */
@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private TbItemMapper itemMapper;
	
	@Autowired
	private TbItemDescMapper itemDescMapper;
	
	@Autowired
	private TbItemParamItemMapper itemParamItemMapper;
	
	@Override
	public TbItem getItemById(long itemId) {
		
		//TbItem item = itemMapper.selectByPrimaryKey(itemId);
		//添加查询条件
		TbItemExample example = new TbItemExample();
		Criteria criteria = example.createCriteria();
		criteria.andIdEqualTo(itemId);
		List<TbItem> list = itemMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			TbItem item = list.get(0);
			return item;
		}
		return null;
	}

	/**
	 * 商品列表查询
	 * <p>Title: getItemList</p>
	 * <p>Description: </p>
	 * @param page
	 * @param rows
	 * @return
	 * @see com.taotao.service.ItemService#getItemList(long, long)
	 */
	@Override
	public EUDataGridResult getItemList(int page, int rows) {
		//查询商品列表
		TbItemExample example = new TbItemExample();
		//分页处理
		PageHelper.startPage(page, rows);
		List<TbItem> list = itemMapper.selectByExample(example);
		//创建一个返回值对象
		EUDataGridResult result = new EUDataGridResult();
		result.setRows(list);
		//取记录总条数
		PageInfo<TbItem> pageInfo = new PageInfo<>(list);
		result.setTotal(pageInfo.getTotal());
		return result;
	}

	@Override
	public TaotaoResult createItem(TbItem item, String desc, String itemParam) throws Exception {
		//item补全
		//生成商品ID
		Long itemId = IDUtils.genItemId();
		item.setId(itemId);
		// '商品状态,1-正常,2-下架,3-删除',
		item.setStatus((byte) 1);
		item.setCreated(new Date());
		item.setUpdated(new Date());
		//插入到数据库
		itemMapper.insert(item);
		//添加商品描述信息
		TaotaoResult result = insertItemDesc(itemId, desc);
		if (result.getStatus() != 200) {
			throw new Exception();
		}
		//添加规格参数
		result = insertItemParamItem(itemId, itemParam);
		if (result.getStatus() != 200) {
			throw new Exception();
		}
		return TaotaoResult.ok();
	}
	/**
	 * 添加商品描述
	 * <p>Title: insertItemDesc</p>
	 * <p>Description: </p>
	 * @param desc
	 */
	private TaotaoResult insertItemDesc(Long itemId, String desc) {
		TbItemDesc itemDesc = new TbItemDesc();
		itemDesc.setItemId(itemId);
		itemDesc.setItemDesc(desc);
		itemDesc.setCreated(new Date());
		itemDesc.setUpdated(new Date());
		itemDescMapper.insert(itemDesc);
		return TaotaoResult.ok();
	}
	
	/**
	 * 添加规格参数
	 * <p>Title: insertItemParamItem</p>
	 * <p>Description: </p>
	 * @param itemId
	 * @param itemParam
	 * @return
	 */
	private TaotaoResult insertItemParamItem(Long itemId, String itemParam) {
		//创建一个pojo
		TbItemParamItem itemParamItem = new TbItemParamItem();
		itemParamItem.setItemId(itemId);
		itemParamItem.setParamData(itemParam);
		itemParamItem.setCreated(new Date());
		itemParamItem.setUpdated(new Date());
		//向表中插入数据
		itemParamItemMapper.insert(itemParamItem);
		
		return TaotaoResult.ok();
		
	}

}

1.5 Controller层

功能分析:接收页面传递过来的数据包括商品和商品描述。

接收表单中的内容,使用一个pojo接收,调用service。

参数:TbItem、TbItemDesc。

返回值:TaotaoResult

ItemController.java

在【taotao-manager-web】项目的【src/main/java】下的【com.taotao.controller】包创建【ItemController.java】

淘淘商城72

package com.taotao.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utils.TaotaoResult;
import com.taotao.pojo.TbItem;
import com.taotao.service.ItemService;

@Controller
public class ItemController {
	@Autowired
	private ItemService itemService;
	
//	商品查询
	@RequestMapping("/item/{itemId}")
	@ResponseBody
	public TbItem getItemById(@PathVariable Long itemId) {
		TbItem item = itemService.getItemById(itemId);
		return item;
	}
	

//	分页
	@RequestMapping("/item/list")
	@ResponseBody
	public EUDataGridResult getItemList(Integer page, Integer rows) {
		EUDataGridResult result = itemService.getItemList(page, rows);
		return result;
	}

	
//	商品添加功能实现
//	商品信息、添加商品描述
	@RequestMapping(value="/item/save", method=RequestMethod.POST)
	@ResponseBody
	private TaotaoResult createItem(TbItem item, String desc) throws Exception {
		TaotaoResult result = itemService.createItem(item, desc);
		return result;
	}
	
}

2 商品规格

2.1 什么是商品规格

规格参数:

规格组

|-规格项:规格值

规律:

1、同一类商品的规格项分组相同。

2、同一类商品的规格项目是相同的。规格项目是跟商品关联。

3、不同商品规格参数的值是不同的

2.2 实现方案

2.2.1 方案一:使用多个表来存储

1、每一类商品有多个分组

2、每个分组下有多个项

3、每个商品对应不同的规格参数

使用二维表来维护规格数据。

表一:规格组信息

列名 类型 长度 可以null 说明
Id Int P 主键(自增长)
group_name varchar 20 规格分组名称
item_cat_id Int F 商品分类id(外键)

表二:规格项信息

列名 类型 长度 可以null 说明
Id Int P 主键(自增长)
param_name varchar 20 规格项目名称
group_id Int F 规格分组id(外键)

表三:商品规格信息

列名 类型 长度 可以null 说明
item_id Int P 商品id(联合主键)
param_id varchar P 规格项id(联合主键)
param_value varchar 500 规格信息
sql语句
SELECT
	pg.group_name,pk.param_name,pv.param_value
FROM
	tb_item_param_value pv
LEFT JOIN tb_item_param_key pk ON pv.param_id = pk.id
LEFT JOIN tb_item_param_group pg ON pk.group_id = pg.id
WHERE
	item_id = 855739

方案一存在的问题:

1、需要创建多张表来描述规格参数之间的关系。

2、查询时需要复杂的sql语句查询。

3、规格参数数据量是商品信息的几十倍,数据量十分庞大。查询时效率很低。

如果要求新添加的商品规格项发生改变,之前的商品不变是不能实现的

2.2.2 方案二:模板

1.1.1. 方案分析

可以使用模板的思路来解决此问题。

模板

每一个商品分类对一个规格参数模板。

[
    {
        "group": "主体",  //组名称
        "params": [ // 记录规格成员
            "品牌",
            "型号",
            "颜色",
            "上市年份",
            "上市月份"
        ]
},
{
        "group": "网络",  //组名称
        "params": [ // 记录规格成员
            "4G",
            "3G,
            "2G"
        ]
}
]

使用模板

每个商品对应一唯一的规格参数。在添加商品时,可以根据规格参数的模板。生成一个表单。保存规格参数时。还可以生成规格参数的json数据。保存到数据库中。

[
    {
        "group": "主体",
        "params": [
            {
                "k": "品牌",
                "v": "苹果(Apple)"
            },
            {
                "k": "型号",
                "v": "iPhone 6 A1589"
            },
{
                "k": "智能机",
                "v": "是 "
            }

        ]
}
]

流程图

数据库存储

优点:

1、不需要做多表管理。

2、如果要求新添加的商品规格项发生改变,之前的商品不变是很简单的。

缺点:

复杂的表单和json之间的转换。对js的编写要求很高。

2.3 创建规格参数模板

2.3.1. 选择商品分类

2.3.1.1功能分析
index.jsp

在【taotao-manager-web】项目中,【src/main/webapp/WEB-INF/jsp】目录下

item-param-list.jsp

在【taotao-manager-web】项目中,【src/main/webapp/WEB-INF/jsp】目录下

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<table class="easyui-datagrid" id="itemParamList" title="商品列表" 
       data-options="singleSelect:false,collapsible:true,pagination:true,url:'/item/param/list',method:'get',pageSize:30,toolbar:itemParamListToolbar">
    <thead>
        <tr>
        	<th data-options="field:'ck',checkbox:true"></th>
        	<th data-options="field:'id',width:60">ID</th>
        	<th data-options="field:'itemCatId',width:80">商品类目ID</th>
        	<th data-options="field:'itemCatName',width:100">商品类目</th>
            <th data-options="field:'paramData',width:300,formatter:formatItemParamData">规格(只显示分组名称)</th>
            <th data-options="field:'created',width:130,align:'center',formatter:TAOTAO.formatDateTime">创建日期</th>
            <th data-options="field:'updated',width:130,align:'center',formatter:TAOTAO.formatDateTime">更新日期</th>
        </tr>
    </thead>
</table>
<div id="itemEditWindow" class="easyui-window" title="编辑商品" data-options="modal:true,closed:true,iconCls:'icon-save',href:'/item-edit'" 
     style="width:80%;height:80%;padding:10px;">
</div>
<script>

	function formatItemParamData(value , index){
		var json = JSON.parse(value);
		var array = [];
		$.each(json,function(i,e){
			array.push(e.group);
		});
		return array.join(",");
	}

    function getSelectionsIds(){
    	var itemList = $("#itemParamList");
    	var sels = itemList.datagrid("getSelections");
    	var ids = [];
    	for(var i in sels){
    		ids.push(sels[i].id);
    	}
    	ids = ids.join(",");
    	return ids;
    }
    
    var itemParamListToolbar = [{
        text:'新增',
        iconCls:'icon-add',
        handler:function(){
        	TAOTAO.createWindow({
        		url : "/item-param-add",
        	});
        }
    },{
        text:'编辑',
        iconCls:'icon-edit',
        handler:function(){
        	$.messager.alert('提示','该功能未实现!');
        }
    },{
        text:'删除',
        iconCls:'icon-cancel',
        handler:function(){
        	var ids = getSelectionsIds();
        	if(ids.length == 0){
        		$.messager.alert('提示','未选中商品规格!');
        		return ;
        	}
        	$.messager.confirm('确认','确定删除ID为 '+ids+' 的商品规格吗?',function(r){
        	    if (r){
        	    	var params = {"ids":ids};
                	$.post("/item/param/delete",params, function(data){
            			if(data.status == 200){
            				$.messager.alert('提示','删除商品规格成功!',undefined,function(){
            					$("#itemParamList").datagrid("reload");
            				});
            			}
            		});
        	    }
        	});
        }
    }];
</script>

item-param-add.jsp

在【taotao-manager-web】项目中,【src/main/webapp/WEB-INF/jsp】目录下

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<table cellpadding="5" style="margin-left: 30px" id="itemParamAddTable" class="itemParam">
	<tr>
		<td>商品类目:</td>
		<td><a href="javascript:void(0)" class="easyui-linkbutton selectItemCat">选择类目</a> 
			<input type="hidden" name="cid" style="width: 280px;"></input>
		</td>
	</tr>
	<tr class="hide addGroupTr">
		<td>规格参数:</td>
		<td>
			<ul>
				<li><a href="javascript:void(0)" class="easyui-linkbutton addGroup">添加分组</a></li>
			</ul>
		</td>
	</tr>
	<tr>
		<td></td>
		<td>
			<a href="javascript:void(0)" class="easyui-linkbutton submit">提交</a>
	    	<a href="javascript:void(0)" class="easyui-linkbutton close">关闭</a>
		</td>
	</tr>
</table>
<div  class="itemParamAddTemplate" style="display: none;">
	<li class="param">
		<ul>
			<li>
				<input class="easyui-textbox" style="width: 150px;" name="group"/>&nbsp;<a href="javascript:void(0)" class="easyui-linkbutton addParam"  title="添加参数" data-options="plain:true,iconCls:'icon-add'"></a>
			</li>
			<li>
				<span>|-------</span><input  style="width: 150px;" class="easyui-textbox" name="param"/>&nbsp;<a href="javascript:void(0)" class="easyui-linkbutton delParam" title="删除" data-options="plain:true,iconCls:'icon-cancel'"></a>						
			</li>
		</ul>
	</li>
</div>
<script style="text/javascript">
	$(function(){
		TAOTAO.initItemCat({
			fun:function(node){
			$(".addGroupTr").hide().find(".param").remove();
				//  判断选择的类目是否已经添加过规格
			  $.getJSON("/item/param/query/itemcatid/" + node.id,function(data){
				  if(data.status == 200 && data.data){
					  $.messager.alert("提示", "该类目已经添加,请选择其他类目。", undefined, function(){
						 $("#itemParamAddTable .selectItemCat").click();
					  });
					  return ;
				  }
				  $(".addGroupTr").show();
			  });
			}
		});
		
		$(".addGroup").click(function(){
			  var temple = $(".itemParamAddTemplate li").eq(0).clone();
			  $(this).parent().parent().append(temple);
			  temple.find(".addParam").click(function(){
				  var li = $(".itemParamAddTemplate li").eq(2).clone();
				  li.find(".delParam").click(function(){
					  $(this).parent().remove();
				  });
				  li.appendTo($(this).parentsUntil("ul").parent());
			  });
			  temple.find(".delParam").click(function(){
				  $(this).parent().remove();
			  });
		 });
		
		$("#itemParamAddTable .close").click(function(){
			$(".panel-tool-close").click();
		});
		
		$("#itemParamAddTable .submit").click(function(){
			var params = [];
			var groups = $("#itemParamAddTable [name=group]");
			groups.each(function(i,e){
				var p = $(e).parentsUntil("ul").parent().find("[name=param]");
				var _ps = [];
				p.each(function(_i,_e){
					var _val = $(_e).siblings("input").val();
					if($.trim(_val).length>0){
						_ps.push(_val);						
					}
				});
				var _val = $(e).siblings("input").val();
				if($.trim(_val).length>0 && _ps.length > 0){
					params.push({
						"group":_val,
						"params":_ps
					});					
				}
			});
			var url = "/item/param/save/"+$("#itemParamAddTable [name=cid]").val();
			$.post(url,{"paramData":JSON.stringify(params)},function(data){
				if(data.status == 200){
					$.messager.alert('提示','新增商品规格成功!',undefined,function(){
						$(".panel-tool-close").click();
    					$("#itemParamList").datagrid("reload");
    				});
				}
			});
		});
	});
</script>
common.js

在【taotao-manager-web】项目中,【src/main/webapp/WEB-INF/js】目录下

选择商品分类后根据选择的商品分类到tb_item_param规格参数模板表中取规格模板,取到了说明此商品分类的规格模板已经添加提示不能添加。

如果没有取得正常添加。

请求的url:

/item/param/query/itemcatid/{itemCatId}

参数:itemCatId,从url中获得

返回值:TaotaoResult

item-param-add.jsp

在【taotao-manager-web】项目中,【src/main/webapp/WEB-INF/jsp】目录下

2.3.1.2 Dao层

从tb_item_param表中根据商品分类id查询内容。

单表操作。可以实现逆向工程的代码。

2.3.1.3 Service层

功能:接收商品分类id。调用mapper查询tb_item_param表,返回结果TaotaoResult接口

ItemParamService.java

在【taotao-manager-service】项目下,【src/main/java】目录下【com.taotao.service】包,【ItemParamService.java】文件

package com.taotao.service;

import com.taotao.common.utils.TaotaoResult;
//创建规格参数模板
public interface ItemParamService {
	TaotaoResult getItemParamByCid(long cid);
}

ItemParamServiceImpl.java

在【taotao-manager-service】项目下,【src/main/java】目录下【com.taotao.service.impl】包,【ItemParamServiceImpl.java】文件

package com.taotao.service.impl;

import java.util.List;

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

import com.taotao.common.utils.TaotaoResult;
import com.taotao.mapper.TbItemParamMapper;
import com.taotao.pojo.TbItemParam;
import com.taotao.pojo.TbItemParamExample;
import com.taotao.pojo.TbItemParamExample.Criteria;
import com.taotao.service.ItemParamService;

/**
 * 商品规格参数模板管理
 * <p>Title: ItemParamServiceImpl</p>
 * <p> Description: </p>
 * <p> Company: www.itcast.com </p>
 * 
 */
@Service
public class ItemParamServiceImpl implements ItemParamService {

	@Autowired
	private TbItemParamMapper itemParamMapper;

	@Override
	public TaotaoResult getItemParamByCid(long cid) {
		TbItemParamExample example = new TbItemParamExample();
		
//		创建查询条件
		Criteria criteria = example.createCriteria();
		criteria.andItemCatIdEqualTo(cid);
		
//		查询结果的返回值
		List<TbItemParam> list = itemParamMapper.selectByExampleWithBLOBs(example);
		// 判断是否查询到结果
		if (list != null && list.size() > 0) {
			return TaotaoResult.ok(list.get(0));
		}

		return TaotaoResult.ok();
	}
}


2.3.1.4 Controller层

接收cid参数。调用Service查询规格参数模板。返回TaotaoResult。返回json数据。

ItemParamController.java

在【taotao-manager-web】项目的【src/main/java】下的【com.taotao.controller】包创建【ItemParamController.java】

package com.taotao.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.utils.TaotaoResult;
import com.taotao.service.ItemParamService;

/**
 * 商品规格参数模板管理Controller
 * <p>Title: ItemParamController</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.com</p> 

 */
@Controller
@RequestMapping("/item/param")
public class ItemParamController {

	@Autowired
	private ItemParamService itemParamService;
	
	@RequestMapping("/query/itemcatid/{itemCatId}")
	@ResponseBody
	public TaotaoResult getItemParamByCid(@PathVariable Long itemCatId) {
		TaotaoResult result = itemParamService.getItemParamByCid(itemCatId);
		return result;
	}	
	
}


2.3.2 提交规格参数模板

2.3.2.1需求分析

首先把页面中所有文本框中的内容转换成json数据。把json字符串提交给后台。保存到规格参数表中。

请求的url:

/item/param/save/{cid}

参数:

String paramData

返回值:

TaotaoResult

2.3.2.2 Dao层

保存规格参数模板,向tb_item_param表添加一条记录。可以使用逆向工程生成的代码。

2.3.2.3 Service层

功能:接收TbItemParam对象。 把对象调用mapper插入到tb_item_param表中。返回TaotaoResult。

ItemParamService.java

在【taotao-manager-service】项目下,【src/main/java】目录下【com.taotao.service】包,【ItemParamService.java】文件

package com.taotao.service;

import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbItemParam;
//创建规格参数模板
public interface ItemParamService {
	
//	选择商品分类
	TaotaoResult getItemParamByCid(long cid);
	
//	提交规格参数模板
	TaotaoResult insertItemParam(TbItemParam itemParam);

}

ItemParamServiceImpl.java

在【taotao-manager-service】项目下,【src/main/java】目录下【com.taotao.service.impl】包,【ItemParamServiceImpl.java】文件

package com.taotao.service.impl;

import java.util.Date;
import java.util.List;

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

import com.taotao.common.utill.TaotaoResult;
import com.taotao.mapper.TbItemParamMapper;
import com.taotao.pojo.TbItemParam;
import com.taotao.pojo.TbItemParamExample;
import com.taotao.pojo.TbItemParamExample.Criteria;
import com.taotao.service.ItemParamService;

/**
 * 商品规格参数模板管理
 * <p>Title: ItemParamServiceImpl</p>
 * <p> Description: </p>
 * <p> Company: www.itcast.com </p>
 * 
 */
@Service
public class ItemParamServiceImpl implements ItemParamService {

	@Autowired
	private TbItemParamMapper itemParamMapper;

	@Override
	public TaotaoResult getItemParamByCid(long cid) {
		TbItemParamExample example = new TbItemParamExample();
		
//		创建查询条件
		Criteria criteria = example.createCriteria();
		criteria.andItemCatIdEqualTo(cid);
		
//		查询结果的返回值
//		selectByExampleWithBLOBs包含大文本列,也就是规格参数模板列
		List<TbItemParam> list = itemParamMapper.selectByExampleWithBLOBs(example);
		// 判断是否查询到结果
		if (list != null && list.size() > 0) {
			return TaotaoResult.ok(list.get(0));
		}

		return TaotaoResult.ok();
	}

	
//	提交规格参数模板
	@Override
	public TaotaoResult insertItemParam(TbItemParam itemParam) {
		//补全pojo
		itemParam.setCreated(new Date());
		itemParam.setUpdated(new Date());
		//插入到规格参数模板表
		itemParamMapper.insert(itemParam);
		return TaotaoResult.ok();
	}

}


2.3.1.4 Controller层

功能:接收cid、规格参数模板。创建一TbItemParam对象。调用Service返回TaotaoResult。返回json数据。

ItemParamController.java

在【taotao-manager-web】项目的【src/main/java】下的【com.taotao.controller】包创建【ItemParamController.java】

package com.taotao.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbItemParam;
import com.taotao.service.ItemParamService;

/**
 * 商品规格参数模板管理Controller
 * <p>Title: ItemParamController</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.com</p> 

 */
@Controller
@RequestMapping("/item/param")
public class ItemParamController {

	@Autowired
	private ItemParamService itemParamService;
	
//	选择商品分类
	@RequestMapping("/query/itemcatid/{itemCatId}")
	@ResponseBody
	public TaotaoResult getItemParamByCid(@PathVariable Long itemCatId) {
		TaotaoResult result = itemParamService.getItemParamByCid(itemCatId);
		return result;
	}	
	
//	提交规格参数模板
	@RequestMapping("/save/{cid}")
	@ResponseBody
	public TaotaoResult insertItemParam(@PathVariable Long cid, String paramData) {
		//创建pojo对象
		TbItemParam itemParam = new TbItemParam();
		itemParam.setItemCatId(cid);
		itemParam.setParamData(paramData);
		TaotaoResult result = itemParamService.insertItemParam(itemParam);
		return result;
	}

}


2.3.3测试

数据库:【tb_item_param】表

2.4 根据规格参数模板生成表单

在商品添加功能中,读取此商品对应的规格模板,生成表单。供使用者添加规格参数。

item-add.jsp

在【taotao-manager-web】项目中,【src/main/webapp/WEB-INF/jsp】目录下

common.js

初始化规格参数模板,读取模板,生成表单

在【taotao-manager-web】项目中,【src/main/webapp/WEB-INF/js】目录下

ItemParamServiceImpl.java

在【taotao-manager-service】项目下,【src/main/java】目录下【com.taotao.service.impl】包,【ItemParamServiceImpl.java】文件

TbItemParamMapper.xml

【taotao-manager-mapper】-【/src/main/java】-【/com/taotao/mapper】-【TbItemParamMapper.xml】

2.5 保存商品的规格参数

提交表单之前,先把规格参数表单中的内容转换成json数据然后跟商品基本信息、商品描述同时提交给后台。保存至数据库。

item-add.jsp

在【taotao-manager-web】项目中,【src/main/webapp/WEB-INF/jsp】目录下

转换后把规格参数的信息放到当前表单的hidden域中:

随着表单的提交同时提交。

Dao层

需要向tb_item_param_item表中添加数据。

Service层

接收规格参数的内容,和商品id。拼装成pojo调用mapper 的方法tb_item_param_item表中添加数据返回TaotaoResult。

ItemService.java

在【taotao-manager-service】项目下,【src/main/java】目录下【com.taotao.service】包,【ItemService.java】文件

package com.taotao.service;

import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbItem;

public interface ItemService {

//	查询商品
	TbItem getItemById(long itemId);
	
//	分页
	EUDataGridResult  getItemList(int page,int rows);
	
//	商品添加功能实现
//	商品信息、添加商品描述
	TaotaoResult createItem(TbItem item, String desc, String itemParam) throws Exception;
}

ItemServiceImpl.java

在【taotao-manager-service】项目下,【src/main/java】目录下【com.taotao.service.impl】包,【ItemServiceImpl.java】文件

package com.taotao.service.impl;

import java.util.Date;
import java.util.List;

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

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.IDUtils;
import com.taotao.mapper.TbItemDescMapper;
import com.taotao.mapper.TbItemMapper;
import com.taotao.mapper.TbItemParamItemMapper;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemDesc;
import com.taotao.pojo.TbItemExample;
import com.taotao.pojo.TbItemExample.Criteria;
import com.taotao.pojo.TbItemParamItem;
import com.taotao.service.ItemService;

/**
 * 商品管理Service
 * <p>Title: ItemServiceImpl</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.com</p> 
 * @author	入云龙
 * @date	2015年9月2日上午10:47:14
 * @version 1.0
 */
@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private TbItemMapper itemMapper;
	
	@Autowired
	private TbItemDescMapper itemDescMapper;
	
	@Autowired
	private TbItemParamItemMapper itemParamItemMapper;
	
	@Override
	public TbItem getItemById(long itemId) {
		
		//TbItem item = itemMapper.selectByPrimaryKey(itemId);
		//添加查询条件
		TbItemExample example = new TbItemExample();
		Criteria criteria = example.createCriteria();
		criteria.andIdEqualTo(itemId);
		List<TbItem> list = itemMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			TbItem item = list.get(0);
			return item;
		}
		return null;
	}

	/**
	 * 商品列表查询
	 * <p>Title: getItemList</p>
	 * <p>Description: </p>
	 * @param page
	 * @param rows
	 * @return
	 * @see com.taotao.service.ItemService#getItemList(long, long)
	 */
	@Override
	public EUDataGridResult getItemList(int page, int rows) {
		//查询商品列表
		TbItemExample example = new TbItemExample();
		//分页处理
		PageHelper.startPage(page, rows);
		List<TbItem> list = itemMapper.selectByExample(example);
		//创建一个返回值对象
		EUDataGridResult result = new EUDataGridResult();
		result.setRows(list);
		//取记录总条数
		PageInfo<TbItem> pageInfo = new PageInfo<>(list);
		result.setTotal(pageInfo.getTotal());
		return result;
	}

	@Override
	public TaotaoResult createItem(TbItem item, String desc, String itemParam) throws Exception {
		//item补全
		//生成商品ID
		Long itemId = IDUtils.genItemId();
		item.setId(itemId);
		// '商品状态,1-正常,2-下架,3-删除',
		item.setStatus((byte) 1);
		item.setCreated(new Date());
		item.setUpdated(new Date());
		//插入到数据库
		itemMapper.insert(item);
		//添加商品描述信息
		TaotaoResult result = insertItemDesc(itemId, desc);
		if (result.getStatus() != 200) {
			throw new Exception();
		}
		//添加规格参数
		result = insertItemParamItem(itemId, itemParam);
		if (result.getStatus() != 200) {
			throw new Exception();
		}
		return TaotaoResult.ok();
	}
	/**
	 * 添加商品描述
	 * <p>Title: insertItemDesc</p>
	 * <p>Description: </p>
	 * @param desc
	 */
	private TaotaoResult insertItemDesc(Long itemId, String desc) {
		TbItemDesc itemDesc = new TbItemDesc();
		itemDesc.setItemId(itemId);
		itemDesc.setItemDesc(desc);
		itemDesc.setCreated(new Date());
		itemDesc.setUpdated(new Date());
		itemDescMapper.insert(itemDesc);
		return TaotaoResult.ok();
	}
	
	/**
	 * 添加规格参数
	 * <p>Title: insertItemParamItem</p>
	 * <p>Description: </p>
	 * @param itemId
	 * @param itemParam
	 * @return
	 */
	private TaotaoResult insertItemParamItem(Long itemId, String itemParam) {
		//创建一个pojo
		TbItemParamItem itemParamItem = new TbItemParamItem();
		itemParamItem.setItemId(itemId);
		itemParamItem.setParamData(itemParam);
		itemParamItem.setCreated(new Date());
		itemParamItem.setUpdated(new Date());
		//向表中插入数据
		itemParamItemMapper.insert(itemParamItem);
		
		return TaotaoResult.ok();
		
	}

}

Controller层

接收规格参数信息,调用Service层保存商品信息及商品描述及商品规格参数。返回taotaoResult.

ItemController.java

在【taotao-manager-web】项目的【src/main/java】下的【com.taotao.controller】包创建【ItemController.java】

淘淘商城72

package com.taotao.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utils.TaotaoResult;
import com.taotao.pojo.TbItem;
import com.taotao.service.ItemService;

@Controller
public class ItemController {
	@Autowired
	private ItemService itemService;
	
//	商品查询
	@RequestMapping("/item/{itemId}")
	@ResponseBody
	public TbItem getItemById(@PathVariable Long itemId) {
		TbItem item = itemService.getItemById(itemId);
		return item;
	}
	

//	分页
	@RequestMapping("/item/list")
	@ResponseBody
	public EUDataGridResult getItemList(Integer page, Integer rows) {
		EUDataGridResult result = itemService.getItemList(page, rows);
		return result;
	}

	
//	商品添加功能实现
//	商品信息、添加商品描述
	@RequestMapping(value="/item/save", method=RequestMethod.POST)
	@ResponseBody
	private TaotaoResult createItem(TbItem item, String desc) throws Exception {
		TaotaoResult result = itemService.createItem(item, desc);
		return result;
	}
	
}

测试

2.6 展示规格参数

当现实商品详情页面时,需要把商品的规格参数根据商品id取出来,生成html展示到页面。

2.6.1. Dao层

根据商品id查询规格参数,单表查询。

2.6.2. Service

接收商品id查询规格参数表。根据返回的规格参数生成html返回html。

ItemParamItemService.java

在【taotao-manager-service】项目下,【src/main/java】目录下【com.taotao.service】包,【ItemParamItemService.java】文件

package com.taotao.service;

public interface ItemParamItemService {
//	展示规格参数
	String getItemParamByItemId(Long itemId);
}

ItemParamItemServiceImpl.java

在【taotao-manager-service】项目下,【src/main/java】目录下【com.taotao.service.impl】包,【ItemParamItemServiceImpl.java】文件

package com.taotao.service.impl;

import java.util.List;
import java.util.Map;

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

import com.taotao.common.utill.JsonUtils;
import com.taotao.mapper.TbItemParamItemMapper;
import com.taotao.pojo.TbItemParamItem;
import com.taotao.pojo.TbItemParamItemExample;
import com.taotao.pojo.TbItemParamItemExample.Criteria;
import com.taotao.service.ItemParamItemService;

//	展示规格参数
@Service
public class ItemParamItemServiceImpl implements ItemParamItemService {

	@Autowired
	private TbItemParamItemMapper itemParamItemMapper;
	
	@Override
	public String getItemParamByItemId(Long itemId) {
		//根据商品id查询规格参数
		TbItemParamItemExample example = new TbItemParamItemExample();
		Criteria criteria = example.createCriteria();
		criteria.andItemIdEqualTo(itemId);
		//执行查询
		List<TbItemParamItem> list = itemParamItemMapper.selectByExampleWithBLOBs(example);
		if (list == null || list.size() == 0) {
			return "";
		}
		//取规格参数信息
		TbItemParamItem itemParamItem = list.get(0);
		String paramData = itemParamItem.getParamData();
		
		//生成html
		// 把规格参数json数据转换成java对象
		List<Map> jsonList = JsonUtils.jsonToList(paramData, Map.class);
		StringBuffer sb = new StringBuffer();
		sb.append("<table cellpadding=\"0\" cellspacing=\"1\" width=\"100%\" border=\"1\" class=\"Ptable\">\n");
		sb.append("    <tbody>\n");
		for(Map m1:jsonList) {
			sb.append("        <tr>\n");
			sb.append("            <th class=\"tdTitle\" colspan=\"2\">"+m1.get("group")+"</th>\n");
			sb.append("        </tr>\n");
			List<Map> list2 = (List<Map>) m1.get("params");
			for(Map m2:list2) {
				sb.append("        <tr>\n");
				sb.append("            <td class=\"tdTitle\">"+m2.get("k")+"</td>\n");
				sb.append("            <td>"+m2.get("v")+"</td>\n");
				sb.append("        </tr>\n");
			}
		}
		sb.append("    </tbody>\n");
		sb.append("</table>");
		return sb.toString();
	}

}

2.6.3. Controller

接收商品id调用Service查询规格参数信息,得到规格参数的html。返回一个逻辑视图。把html展示到页面。

package com.taotao.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.taotao.service.ItemParamItemService;

//展示商品规格
@Controller
public class ItemParamItemController {

	@Autowired
	private ItemParamItemService itemParamItemService;
	
	@RequestMapping("/showitem/{itemId}")
	public String showItemParam(@PathVariable Long itemId, Model model) {
		String string = itemParamItemService.getItemParamByItemId(itemId);
		model.addAttribute("itemParam", string);
		return "item";
	}
}

2.6.4 item.jsp

在【taotao-manager-web】项目中,【src/main/webapp/WEB-INF/jsp】目录下

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${itemParam}
</body>
</html>

2.6.5 运行项目

猜你喜欢

转载自blog.csdn.net/weixin_46267445/article/details/118177214