SSM到Spring Boot-从零开发校园商铺平台七(商品类别模块)

17 篇文章 0 订阅

商品类别列表从前端到后端

ProductCategoryDao

public interface ProductCategoryDao {
    /**
     * 通过商品shop id 查询店铺商品类别
     * @param shopId
     * @return
     */
    List<ProductCategory> queryProductCategoryList(long shopId);
}

ProductCategoryDao.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.imooc.o2o.dao.ProductCategoryDao">
    <select id="queryProductCategoryList"
            resultType="com.imooc.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>
</mapper>

测试

public class ProductCategoryDaoTest extends BaseTest {
    @Autowired
    private ProductCategoryDao productCategoryDao;
    @Test
    public void queryProductCategoryList() {
        long shopId=1;
        List<ProductCategory> productCategoryList =
                productCategoryDao.queryProductCategoryList(shopId);
        System.out.println("该店铺自定义类别数为:"+productCategoryList.size());
    }
}

ProductCategoryService

public interface ProductCategoryService {
    /**
     * 查询指定某个店铺下所有商品类别信息
     * @param shopId
     * @return
     */
    List<ProductCategory> getProductCategoryList(long shopId);
}

ProductCategoryServiceImpl

@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {
    @Autowired
    private ProductCategoryDao productCategoryDao;

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

enums/ProductCategoryStateEnum

package com.imooc.o2o.enums;

public enum ProductCategoryStateEnum {
	SUCCESS(1, "创建成功"), INNER_ERROR(-1001, "操作失败"), EMPTY_LIST(-1002, "添加数少于1");

	private int state;

	private String stateInfo;

	private ProductCategoryStateEnum(int state, String stateInfo) {
		this.state = state;
		this.stateInfo = stateInfo;
	}

	public int getState() {
		return state;
	}

	public String getStateInfo() {
		return stateInfo;
	}

	public static ProductCategoryStateEnum stateOf(int index) {
		for (ProductCategoryStateEnum state : values()) {
			if (state.getState() == index) {
				return state;
			}
		}
		return null;
	}

}

dto/Result

package com.imooc.o2o.dto;

/**
 * 封装json对象,所有返回结果都使用它
 * @param <T>
 */
public class Result<T> {
    private boolean success;//返回成功标志
    private T data;//成功时返回的数据
    private String errorMsg;//错误信息
    private int errorCode;

    public Result(){

    }

    //成功时的构造器
    public Result(boolean success,T data){
        this.success =success;
        this.data =data;
    }

    //错误时的构造器
    public Result(boolean success,int errorCode,String errorMsg){
        this.success=success;
        this.errorMsg = errorMsg;
        this.errorCode =errorCode;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
}

ProductCategoryManagementController

package com.imooc.o2o.web.shopadmin;

import com.imooc.o2o.dto.Result;
import com.imooc.o2o.entity.Product;
import com.imooc.o2o.entity.ProductCategory;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.enums.ProductCategoryStateEnum;
import com.imooc.o2o.service.ProductCategoryService;
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 javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/shopadmin")
public class ProductCategoryManagementController {
    @Autowired
    private ProductCategoryService productCategoryService;

    //使用Result封装json对象,所有返回结果都使用它
    @RequestMapping(value = "/getproductcategorylist",method = RequestMethod.GET)
    @ResponseBody
    private Result<List<ProductCategory>> getProductCategoryList(HttpServletRequest request){

        Shop currenShop = (Shop)request.getSession().getAttribute(
                "currentShop");
        List<ProductCategory> list = null;
        if(currenShop!=null&&currenShop.getShopId()>0){
            list=
                    productCategoryService.getProductCategoryList(currenShop.getShopId());
            return new Result<List<ProductCategory>>(true,list);
        }else {
            ProductCategoryStateEnum ps = ProductCategoryStateEnum.INNER_ERROR;
            return new Result<List<ProductCategory>>(false,ps.getState(),
                    ps.getStateInfo());
        }
    }
}

在ShopAdminController中加入

    @RequestMapping(value = "/productcategorymanagement")
    public String productCategoryManage(){
        return "shop/productcategorymanagement";
    }

productcategorymanagement.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/shop/productcategorymanagement.js'
        charset='utf-8'></script>
</body>
</html>

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;
}

js 

$(function() {
    var shopId = 1;
    var listUrl = '/shopadmin/getproductcategorylist';
    var addUrl = '/shopadmin/addproductcategorys';
    var deleteUrl = '/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,
                        shopId : shopId
                    },
                    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();

        });
});

商品类别批量添加

ProductCategoryDao添加

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

ProductCategoryDao.xml

 <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>

测试

    @Test
    public void testBatchInsertProductCategory(){
        ProductCategory productCategory = new ProductCategory();
        productCategory.setProductCategoryName("商品类别1");
        productCategory.setPriority(1);
        productCategory.setCreateTime(new Date());
        productCategory.setShopId(1L);
        ProductCategory productCategory2 = new ProductCategory();
        productCategory2.setProductCategoryName("商品类别2");
        productCategory2.setPriority(2);
        productCategory2.setCreateTime(new Date());
        productCategory2.setShopId(1L);
        List<ProductCategory> productCategoryList=
                new ArrayList<ProductCategory>();
        productCategoryList.add(productCategory);
        productCategoryList.add(productCategory2);
        int effectedNum=
                productCategoryDao.batchInsertProductCategory(productCategoryList);
        System.out.println(effectedNum);
    }

ProductCategoryService中添加

public ProductCategoryExecution betchAddProductCategory(List<ProductCategory> productCategoryList)
            throws ProductCategoryOperationException;

ProductCategoryServiceImpl添加

@Override
    @Transactional
    public ProductCategoryExecution betchAddProductCategory(List<ProductCategory> productCategoryList) throws ProductCategoryOperationException {
        if(productCategoryList!=null&&productCategoryList.size()>0){
            try{
                int effectedNum =
                        productCategoryDao.batchInsertProductCategory(productCategoryList);
                if(effectedNum<=0){
                    throw new ProductCategoryOperationException("店铺类别创建失败");
                }else{
                    return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
                }
            }catch (Exception e){
                throw new ProductCategoryOperationException(
                        "batchAddProductCategory error:"+e.getMessage());
            }
        }else{
            return new ProductCategoryExecution(ProductCategoryStateEnum.EMPTY_LIST);
        }
    }

ProductCategoryManagementController中添加

@RequestMapping(value = "/addproductcategorys", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> addProductCategorys(@RequestBody List<ProductCategory> productCategoryList, HttpServletRequest request) {
        Map<String,Object> modelMap = new HashMap<String,Object>();
        //取出curretnShop,尽可能少依赖于前台传的数据
        Shop currentShop =(Shop)request.getSession().getAttribute(
                "currentShop");
        //给每一个PeroductCategory设置shopId
        for(ProductCategory pc:productCategoryList){
            pc.setShopId(currentShop.getShopId());
        }
        if(productCategoryList!=null&&productCategoryList.size()>0){
            try {
                ProductCategoryExecution pe =
                        productCategoryService.betchAddProductCategory(productCategoryList);
                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;
    }

exceptions/ProductCategoryOperationException

package com.imooc.o2o.exceptions;

import java.io.Serializable;

/**
 *
 */
public class ProductCategoryOperationException extends RuntimeException{


    private static final long serialVersionUID = 1182563719599527969L;

    public ProductCategoryOperationException(String msg){
        super(msg);
    }
}

dto/ProductCategoryExecution

package com.imooc.o2o.dto;

import com.imooc.o2o.entity.ProductCategory;
import com.imooc.o2o.enums.ProductCategoryStateEnum;

import java.util.List;

public class ProductCategoryExecution {
    //结果状态
    private int state;
    //状态标识
    private String stateInfo;

    private List<ProductCategory> productCategoryList;

    public ProductCategoryExecution(){

    }

    //操作失败的时候使用的构造器
    public ProductCategoryExecution(ProductCategoryStateEnum stateEnum){
        this.state = stateEnum.getState();
        this.stateInfo = stateEnum.getStateInfo();
    }

    //操作成功的时候的构造器
    public ProductCategoryExecution(ProductCategoryStateEnum stateEnum,
                                    List<ProductCategory> productCategoryList){
        this.state = stateEnum.getState();
        this.stateInfo=stateEnum.getStateInfo();
        this.productCategoryList=productCategoryList;
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public String getStateInfo() {
        return stateInfo;
    }

    public void setStateInfo(String stateInfo) {
        this.stateInfo = stateInfo;
    }

    public List<ProductCategory> getProductCategoryList() {
        return productCategoryList;
    }

    public void setProductCategoryList(List<ProductCategory> productCategoryList) {
        this.productCategoryList = productCategoryList;
    }
}

商品类别删除

ProductCateporyDao

 /**
     * 删除指定商品类型
     * @param productCategoryId
     * @param shopId
     * @return
     */
    int deleteProductCategory(@Param("productCategoryId")long productCategoryId,@Param("shopId")long shopId);

ProductCateporyDao.xml

<delete id="deleteProductCategory">
        delete from
        tb_product_category
        where
        product_category_id=#{productCategoryId}
        and shop_id=#{shopId}
    </delete>

ProductCateporyService

/**
     * 将此类别下的商品里的类别id置为空,在删除掉该商品的类别
     * @param productCategoryId
     * @param shopId
     * @return
     * @throws ProductCategoryOperationException
     */
    ProductCategoryExecution deleteProductCategory(long productCategoryId,
                                                   long shopId) throws ProductCategoryOperationException;

ProductCateporyServiceImpl

 @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 ProductCategoryOperationException("商品类别删除失败");
            }else {
                return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
            }
        }catch (Exception e){
            throw new ProductCategoryOperationException(
                    "deleteproductcategory error"+e.getMessage());
        }
    }

ProductCategoryManagementController

 @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 {
                //取出curretnShop,尽可能少依赖于前台传的数据
                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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值