7-2 product category list shows dao, service, controller, web, resultType and resultMap

Keywords: Javascript JSON Mobile Session

I. Development of Dao layer

1. Develop dao interface

public interface ProductCategoryDao {
	/**
	 * Query the commodity category of the shop through the shop id
	 * @param shopId
	 * @return List<ProductCategory>
	 */
	List<ProductCategory> queryProductCategoryList(long shopId);
}

2. Develop dao implementation class

resultType is the data that returns a table

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

Comparison: resultMap is to return data of multiple tables, and define < resultMap > label on it

	<resultMap type="com.imooc.o2o.entity.Shop" id="shopMap">
		<id column="shop_id" property="shopId" />
		<result column="shop_name" property="shopName" />
		<result column="shop_desc" property="shopDesc" />
		<result column="shop_addr" property="shopAddr" />
		<result column="phone" property="phone" />
		<result column="shop_img" property="shopImg" />
		<result column="priority" property="priority" />
		<result column="create_time" property="createTime" />
		<result column="last_edit_time" property="lastEditTime" />
		<result column="enable_status" property="enableStatus" />
		<result column="advice" property="advice" />
		<association property="area" column="area_id"
			javaType="com.imooc.o2o.entity.Area">
			<id column="area_id" property="areaId" />
			<result column="area_name" property="areaName" />
		</association>
		<association property="shopCategory" column="shop_category_id"
			javaType="com.imooc.o2o.entity.ShopCategory">
			<id column="shop_category_id" property="shopCategoryId" />
			<result column="shop_category_name" property="shopCategoryName" />
		</association>
		<association property="owner" column="user_id"
			javaType="com.imooc.o2o.entity.PersonInfo">
			<id column="user_id" property="userId" />
			<result column="name" property="name" />
		</association>
	</resultMap>
	<select id="queryShopList" resultMap="shopMap">
	<!-- No need here parameterType Because Dao Interface has three parameters -->
	SELECT
		s.shop_id,
		s.shop_name,
		s.shop_desc,
		s.shop_addr,
		s.phone,
		s.shop_img,
		s.priority,
		s.create_time,
		s.last_edit_time,
		s.enable_status,
		s.advice,
		a.area_id,
		a.area_name,
		sc.shop_category_id,
		sc.shop_category_name
		FROM
		tb_shop s,
		tb_area a,
		tb_shop_category sc
		<where>
			<if test="shopCondition.shopCategory!=null and 
			shopCondition.shopCategory.shopCategoryId!=null">
				and s.shop_category_id = #{shopCondition.shopCategory.shopCategoryId}
			</if>
			<if test="shopCondition.area!=null and 
			shopCondition.area.areaId!=null">
				and s.area_id = #{shopCondition.area.areaId}
			</if>
			<if test="shopCondition.shopName!=null">
				and s.shop_name like '%${shopCondition.shopName}%'
			</if>
			<if test="shopCondition.enableStatus!=null">
				and s.enable_status = #{shopCondition.enableStatus}
			</if>
			<if test="shopCondition.owner!=null and shopCondition.owner.userId!=null">
				and s.owner_id = #{shopCondition.owner.userId}
			</if>
		AND
		s.area_id=a.area_id
		AND
		s.shop_category_id = sc.shop_category_id
		</where>
		ORDER BY
		s.priority
		DESC
		LIMIT #{rowIndex},#{pageSize};
	</select>

II. Develop service layer

1. service interface

public interface ProductCategoryService {
	/**
	 * Query all product category information under the specified store
	 * @param shopId
	 * @return
	 */
	List<ProductCategory> getProductCategoryList(long shopId);
}

2. service implementation class

@Service
public class ProductCategoryServiceImpl implements ProductCategoryService{
	@Autowired
	private ProductCategoryDao productCategoryDao;
	@Override
	public List<ProductCategory> getProductCategoryList(long shopId) {
		// TODO Auto-generated method stub
		List<ProductCategory> productCategoryList = productCategoryDao.queryProductCategoryList(shopId);
			return productCategoryList;
	}

}

III. Development of controller layer

@Controller
@RequestMapping("/shopadmin")
public class ProductCategoryManagementController {
	@Autowired
	private ProductCategoryService productCategoryService;
	@RequestMapping(value="/getproductcategorylist", method=RequestMethod.GET)
	@ResponseBody
	private Result<List<ProductCategory>> getProductCategoryList(HttpServletRequest request){
  //Here, the shop can be obtained from the session, which is in the previous ShopManagementController 
  //shopid has been added to getshopmanagementinfo	
    	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());
		}
	}
}

Class Result

Similar to modelmap, where multiple results are saved, only one Result is saved, so the Result is developed

/**
 * Encapsulate the json object and use it for all returned results
 * @author shawn
 *
 * @param <T>
 */
public class Result<T> {
	private boolean success;//Success flag
	private T data;//Data returned on success
	private String errorMsg;//error message
	private int errorCode;//Status code
	public Result() {
		
	}
	//Constructor on success
	public Result(boolean success,T data) {
		this.success = success;
		this.data = data;
	}
	//Constructor on error
	public  Result(boolean success,int errorCode,String errorMsg) {
		this.success = success;
		this.errorCode = errorCode;
		this.errorMsg = errorMsg;
	}
	public  boolean isSuccess() {
		return 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;
	}
	public void setSuccess(boolean success) {
		this.success = success;
	}
	
}

Enumeration class ProductCategoryStateEnum

public enum ProductCategoryStateEnum {
	SUCCESS(1, "Create success"), INNER_ERROR(-1001, "operation failed"), EMPTY_LIST(-1002, "Add less than 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;
	}
}

 

test

Browser input route http://localhost:8080/o2oDemo/shopadmin/getproductcategorylist

V. development front end

1. Write productcategorymanagement.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Commodity classification management</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">
		<a class="button button-link button-nav pull-left back"
			href="javascript:history.back(-1)"> <span class="icon icon-left"></span> Return
		</a>
		<h1 class="title">Commodity classification management</h1>
	</header>
	<div class="content">
		<div class="content-block">
			<div class="row row-product-category">
				<div class="col-33">category</div>
				<div class="col-33">priority</div>
				<div class="col-33">operation</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">Newly added</a>
				</div>
				<div class="col-50">
					<a href="#"Class =" button button big button fill "id =" submit "> 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>

2. Write productcategorymanagement.js

$(function() {
	var listUrl = '/o2oDemo/shopadmin/getproductcategorylist';
	var addUrl = '/o2oDemo/shopadmin/addproductcategorys';
	var deleteUrl = '/o2oDemo/shopadmin/removeproductcategory';
	getList();
	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
													+ '">delete</a></div>'
													+ '</div>';
										});
								$('.category-wrap').append(tempHtml);
							}
						});
	}
	$('#new')
			.click(
					function() {
						var tempHtml = '<div class="row row-product-category temp">'
								+ '<div class="col-33"><input class="category-input category" type="text" placeholder="Classification name"></div>'
								+ '<div class="col-33"><input class="category-input priority" type="number" placeholder="priority"></div>'
								+ '<div class="col-33"><a href="#"Class =" button delete "> delete < / a > < div > '
								+ '</div>';
						$('.category-wrap').append(tempHtml);
					});
	$('#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('Submitted successfully!');
					getList();
				} else {
					$.toast('Failed to submit!');
				}
			}
		});
	});

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

			});
	$('.category-wrap').on('click', '.row-product-category.now .delete',
			function(e) {
				var target = e.currentTarget;
				$.confirm('Are you sure??', function() {
					$.ajax({
						url : deleteUrl,
						type : 'POST',
						data : {
							productCategoryId : target.dataset.id
						},
						dataType : 'json',
						success : function(data) {
							if (data.success) {
								$.toast('Delete successfully!');
								getList();
							} else {
								$.toast('Delete failed!');
							}
						}
					});
				});
			});
});

3. Write productcategorymanagement.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;
}

4. Introduce js and css into html

 

5. Define route by ShopAdminController

The reason for this routing is that the view parser is configured in spring-web.xml to parse the request into / WEB-INF/html/***.html

@Controller
@RequestMapping(value="shopadmin",method= {RequestMethod.GET})
public class ShopAdminController {
	@RequestMapping(value="/productcategorymanagement",method=RequestMethod.GET)
	public String productCategoryManage() {
		return "shop/productcategorymanagement";
	}
}

 

In this way, input in the browser http://localhost:8080/o2oDemo/shopadmin/shopmanagement?shopId=1

Get into

Click category management

Posted by riyaz on Sat, 09 Nov 2019 09:12:52 -0800