一、优化校验:
package com.miaosha.project.validator;
import java.util.HashMap;
import java.util.Map;
public class ValidationResult {
private boolean hasErrors = false;
private Map<String,String> errorMsgMap = new HashMap<>();
public boolean isHasErrors() {
return hasErrors;
}
public void setHasErrors(boolean hasErrors) {
this.hasErrors = hasErrors;
}
public Map<String, String> getErrorMsgMap() {
return errorMsgMap;
}
public void setErrorMsg(Map<String, String> errorMsg) {
this.errorMsgMap = errorMsgMap;
}
//实现通用的通过格式化字符串信息获取错误结果的msg方法
public String getErrMsg(){
return org.apache.commons.lang3.StringUtils.join(errorMsgMap.values().toArray(),",");
}
}
package com.miaosha.project.validator;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
@Component
public class ValidatorImpl implements InitializingBean {
private Validator validator;
//实现校验方法并返回校验结果
public ValidationResult validate(Object bean){
final ValidationResult result = new ValidationResult();
Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(bean);
if(constraintViolationSet.size()>0){
//有错误
result.setHasErrors(true);
constraintViolationSet.forEach(constraintViolation -> {
String errMsg = constraintViolation.getMessage();
String propertyName = constraintViolation.getPropertyPath().toString();
result.getErrorMsgMap().put(propertyName,errMsg);
});
}
return result;
}
@Override
public void afterPropertiesSet() throws Exception {
//将hibernate validator通过工厂的初始化方式使其实例化
this.validator = Validation.buildDefaultValidatorFactory().getValidator();
}
}
package com.miaosha.project.service.model;
import org.mybatis.spring.annotation.MapperScan;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
public class UserModel {
private Integer id;
@NotBlank(message = "用户名不能为空")
private String name;
@NotNull(message = "性别不能不填")
private Byte gender;
@NotNull(message = "年龄不能不填")
@Min(value = 0,message = "年龄必须大于0岁")
@Max(value = 150,message = "年龄不能大于150岁")
private Integer age;
@NotBlank(message = "手机号不能为空")
private String telphone;
private String risterMode;
private String thirdPartyId;
@NotBlank(message = "密码不能为空")
private String encrptPassword;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Byte getGender() {
return gender;
}
public void setGender(Byte gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getTelphone() {
return telphone;
}
public void setTelphone(String telphone) {
this.telphone = telphone;
}
public String getRisterMode() {
return risterMode;
}
public void setRisterMode(String risterMode) {
this.risterMode = risterMode;
}
public String getThirdPartyId() {
return thirdPartyId;
}
public void setThirdPartyId(String thirdPartyId) {
this.thirdPartyId = thirdPartyId;
}
public String getEncrptPassword() {
return encrptPassword;
}
public void setEncrptPassword(String encrptPassword) {
this.encrptPassword = encrptPassword;
}
}
二、新增商品
Create Table |
|
Create Table |
CREATE TABLE `item_stock` ( `id` int(11) NOT NULL AUTO_INCREMENT, `stock` int(11) NOT NULL DEFAULT '0', `item_id` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
ItemStockDOMapper.xml新增
<select id="selectByItemId" parameterType="java.lang.Integer" resultMap="BaseResultMap">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Mon Jan 14 13:56:19 CST 2019.
-->
select
<include refid="Base_Column_List" />
from item_stock
where item_id = #{itemId,jdbcType=INTEGER}
</select>
在 的
insert和insertSelective里增加
useGeneratedKeys="true" keyProperty="id
package com.miaosha.project.service.model;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
public class ItemModel {
private Integer id;
//商品名称
@NotBlank(message = "商品名称不能为空")
private String title;
//商品价格
@NotNull(message = "商品价格不能为空")
@Min(value = 0,message = "商品价格必须大于0")
private BigDecimal price;
//商品库存
@NotNull(message = "库存不能不填")
private Integer stock;
//商品描述
private String description;
//商品销量
private Integer sales;
//商品描述图片imgUrl
@NotBlank(message = "图片信息不能为空")
private String imgUrl;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getSales() {
return sales;
}
public void setSales(Integer sales) {
this.sales = sales;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}
package com.miaosha.project.service;
import com.miaosha.project.error.BusinessException;
import com.miaosha.project.service.model.ItemModel;
import java.util.List;
public interface ItemService {
//创建商品
ItemModel createItem(ItemModel itemModel) throws BusinessException;
//商品列表浏览
List<ItemModel> listItem();
//商品详情页浏览
ItemModel getItemById(Integer id);
}
package com.miaosha.project.service.impl;
import com.miaosha.project.dao.ItemDOMapper;
import com.miaosha.project.dao.ItemStockDOMapper;
import com.miaosha.project.dataObject.ItemDO;
import com.miaosha.project.dataObject.ItemStockDO;
import com.miaosha.project.error.BusinessException;
import com.miaosha.project.error.EmBusinessError;
import com.miaosha.project.service.ItemService;
import com.miaosha.project.service.model.ItemModel;
import com.miaosha.project.validator.ValidationResult;
import com.miaosha.project.validator.ValidatorImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;
@Service
public class ItemServiceImpl implements ItemService {
@Autowired
private ValidatorImpl validator;
@Autowired
private ItemDOMapper itemDOMapper;
@Autowired
private ItemStockDOMapper itemStockDOMapper;
private ItemDO convertItemDOFromItemModel(ItemModel itemModel){
if(itemModel == null){
return null;
}
ItemDO itemDO = new ItemDO();
BeanUtils.copyProperties(itemModel,itemDO);
itemDO.setPrice(itemModel.getPrice().doubleValue());
return itemDO;
}
private ItemStockDO convertItemStockDOFromItemModel(ItemModel itemModel){
if(itemModel == null){
return null;
}
ItemStockDO itemStockDO = new ItemStockDO();
itemStockDO.setId(itemModel.getId());
itemStockDO.setStock(itemModel.getStock());
return itemStockDO;
}
@Override
@Transactional
public ItemModel createItem(ItemModel itemModel) throws BusinessException {
//校验入参
ValidationResult result = validator.validate(itemModel);
if(result.isHasErrors()){
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg());
}
//转换itemmodel->dataobject
ItemDO itemDO = this.convertItemDOFromItemModel(itemModel);
//写入数据库
itemDOMapper.insertSelective(itemDO);
itemModel.setId(itemDO.getId());
ItemStockDO itemStockDO = this.convertItemStockDOFromItemModel(itemModel);
itemStockDOMapper.insertSelective(itemStockDO);
//返回创建完成的对象
return this.getItemById(itemModel.getId());
}
@Override
public List<ItemModel> listItem() {
return null;
}
@Override
public ItemModel getItemById(Integer id) {
ItemDO itemDO = itemDOMapper.selectByPrimaryKey(id);
if(itemDO == null){
return null;
}
//操作获得库存数量
ItemStockDO itemStockDO = itemStockDOMapper.selectByItemId(itemDO.getId());
//将dataobject->model
ItemModel itemModel = this.convertModelFromDataObject(itemDO,itemStockDO);
return itemModel;
}
private ItemModel convertModelFromDataObject(ItemDO itemDO,ItemStockDO itemStockDO){
ItemModel itemModel = new ItemModel();
BeanUtils.copyProperties(itemDO,itemModel);
itemModel.setPrice(new BigDecimal(itemDO.getPrice()));
itemModel.setStock(itemStockDO.getStock());
return itemModel;
}
}
package com.miaosha.project.controller.viewObject;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
public class ItemVO {
private Integer id;
//商品名称
@NotBlank(message = "商品名称不能为空")
private String title;
//商品价格
private BigDecimal price;
//商品库存
private Integer stock;
//商品描述
private String description;
//商品销量
private Integer sales;
//商品描述图片imgUrl
private String imgUrl;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getSales() {
return sales;
}
public void setSales(Integer sales) {
this.sales = sales;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}
package com.miaosha.project.controller;
import com.miaosha.project.controller.viewObject.ItemVO;
import com.miaosha.project.error.BusinessException;
import com.miaosha.project.response.CommonReturnType;
import com.miaosha.project.service.ItemService;
import com.miaosha.project.service.model.ItemModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.math.BigDecimal;
@Controller("/item")
@RequestMapping("/item")
@CrossOrigin(allowedHeaders = "*",allowCredentials = "true")
public class ItemController extends BaseController{
@Autowired
private ItemService itemService;
//创建商品的controller
public CommonReturnType createItem(@RequestParam(name="title") String title,
@RequestParam(name="description") String description,
@RequestParam(name="price")BigDecimal price,
@RequestParam(name="stock") Integer stock,
@RequestParam(name="imgUrl") String imgUrl) throws BusinessException {
//封装service请求用来创建商品
ItemModel itemModel = new ItemModel();
itemModel.setTitle(title);
itemModel.setDescription(description);
itemModel.setPrice(price);
itemModel.setStock(stock);
itemModel.setImgUrl(imgUrl);
ItemModel itemModelForReturn = itemService.createItem(itemModel);
ItemVO itemVO = covertVoFromModel(itemModelForReturn);
return CommonReturnType.create(itemVO);
}
private ItemVO covertVoFromModel(ItemModel itemModel){
if(itemModel == null){
return null;
}
ItemVO itemVO = new ItemVO();
BeanUtils.copyProperties(itemModel,itemVO);
return itemVO;
}
}
UserPasswordDOMapper.xml修改:(启动后不再报错)
修改xml文件会造成运用mapper进行insertSelective的时候失败
三、商品详情页浏览:
四、商品列表:
<html>
<head>
<meta charset="utf-8">
<link href="static/assets/global/plugins/bootstrap/css/bootstrap.min.css" style="stylesheet" type="text/css"/>
<link href="static/assets/global/css/components.css" rel="stylesheet" type="text/css"/>
<link href="static/assets/admin/pages/css/login.css" rel="stylesheet" type="text/css"/>
<script src="static/assets/global/plugins/jquery-1.11.0.min.js" type="text/javascript"></script
</head>
<body >
<div class="content">
<h3 class="form-title">商品列表浏览</h3>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>商品名</th>
<th>商品图片</th>
<th>商品描述</th>
<th>商品价格</th>
<th>商品库存</th>
<th>商品销量</th>
</tr>
</thead>
<tbody id="container">
</tbody>
</table>
</div>
</div>
</body>
<script>
//定义全局商品数组信息
var g_itemList = [];
jQuery(document).ready(function(){
$.ajax({
type:"GET",
url:"http://localhost:8080/item/list",
xhrFields:{withCredentials:true},
success:function(data){
if(data.status == "success"){
g_itemList = data.data;
reloadDom();
}else{
alert("获取商品信息失败,原因为"+data.data.errMsg);
}
},
error:function(data){
alert("获取商品信息失败,原因为"+data.responseText);
}
});
});
function reloadDom() {
for(var i = 0;i<g_itemList.length;i++){
var itemVO = g_itemList[i];
var dom = "<tr data-id='"+itemVO.id+"' id='itemDetail"+itemVO.id+"'><td>"+itemVO.title+"</td><td><img style='width:100px;Height:auto;' src='"+itemVO.imgUrl+"'/></td><td>"+itemVO.description+"</td><td>"+itemVO.price+"</td><td>"+itemVO.stock+"</td><td>"+itemVO.sales+"</td></tr>";
$("#container").append($(dom));
$("#itemDetail"+itemVO.id).on("click",function(e){
window.location.href = "getitem.html?id="+$(this).data("id");
});
}
}
</script>
</html>
<html>
<head>
<meta charset="utf-8">
<link href="static/assets/global/plugins/bootstrap/css/bootstrap.min.css" style="stylesheet" type="text/css"/>
<link href="static/assets/global/css/components.css" rel="stylesheet" type="text/css"/>
<link href="static/assets/admin/pages/css/login.css" rel="stylesheet" type="text/css"/>
<script src="static/assets/global/plugins/jquery-1.11.0.min.js" type="text/javascript"></script
</head>
<body class="login">
<div class="content">
<h3 class="form-title">商品详情</h3>
<label class="form-group">
<label class="control-label">商品名</label>
<div>
<label class="control-label" id="title" />
</div>
</label>
<div class="form-group">
<label class="control-label">商品描述</label>
<div>
<label class="control-label" id="description" />
</div>
</div>
<div class="form-group">
<label class="control-label">价格</label>
<div>
<label class="control-label" id="price" />
</div>
</div>
<div class="form-group">
<!--<label class="control-label">图片</label>-->
<div>
<img style="width:200px;height:auto" id="imgUrl"/>
</div>
</div>
<div class="form-group">
<label class="control-label">库存</label>
<div>
<label class="control-label" id="stock" />
</div>
</div>
<div class="form-group">
<label class="control-label">销量</label>
<div>
<label class="control-label" id="sales" />
</div>
</div>
</div>
</body>
<script>
function getParam(paramName) {
paramValue = "", isFound = !1;
if (this.location.search.indexOf("?") == 0 && this.location.search.indexOf("=") > 1) { arrSource = unescape(this.location.search).substring(1, this.location.search.length).split("&"), i = 0;
while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
}
return paramValue == "" && (paramValue = null), paramValue
}
var g_itemVO = {};
jQuery(document).ready(function(){
$.ajax({
type:"GET",
url:"http://localhost:8080/item/get",
data:{
"id":getParam("id"),
},
xhrFields:{withCredentials:true},
success:function(data){
if(data.status == "success"){
g_itemVO = data.data;
reloadDom();
}else{
alert("获取信息失败,原因为"+data.data.errMsg);
}
},
error:function(data){
alert("获取信息失败,原因为"+data.responseText);
}
});
});
function reloadDom() {
$("#title").text(g_itemVO.title);
$("#description").text(g_itemVO.description);
$("#stock").text(g_itemVO.stock);
$("#price").text(g_itemVO.price);
$("#imgUrl").attr("src",g_itemVO.imgUrl);
$("#sales").text(g_itemVO.sales);
}
</script>
</html>