SSM到Spring Boot-從零開發校園商鋪平臺七(商品類別模塊)

商品類別列表從前端到後端

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章