第185天学习打卡(项目 谷粒商城27 JSR303自定义校验注解 SPU SKU 属性分组效果前端组件抽取 父子组件交互)

Posted doudoutj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第185天学习打卡(项目 谷粒商城27 JSR303自定义校验注解 SPU SKU 属性分组效果前端组件抽取 父子组件交互)相关的知识,希望对你有一定的参考价值。

JSR303自定义校验注解

image-20210712100335853

gulimall-common valid

ListValue.java

package com.doudou.common.valid;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Documented
@Constraint(validatedBy = {ListValueConstraintValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ListValue {
    String message() default "{com.doudou.common.valid.ListValue.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
    int[] vals() default {};
}

ListValueConstraintValidator.java

package com.doudou.common.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {
    private Set<Integer> set = new HashSet<>();
    //初始化方法
    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] vals = constraintAnnotation.vals();
        //这里是进行非空判断
        for(int val : vals){
            set.add(val);
        }


    }
     //判断是否校验成功

    /**
     *
     * @param value 需要校验的值
     * @param Context
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext Context) {

        return set.contains(value);
    }
}

ValidationMessage.properties

com.doudou.common.valid.ListValue.message=必须提交指定的值

gulimall-product controller

BrandEntity .java

package com.doudou.gulimall.product.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;

import com.doudou.common.valid.AddGroup;
import com.doudou.common.valid.ListValue;
import com.doudou.common.valid.UpdateGroup;
import lombok.Data;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;


/**
 * 品牌
 *
 * @author doudoutj111

 * @date 2021-06-19 17:24:02
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@NotNull(message = "修改必须指定品牌id", groups = {UpdateGroup.class})
	@Null(message = "新增不能指定id", groups = {AddGroup.class})
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 */
	@NotBlank(message = "品牌名必须提交", groups = {AddGroup.class, UpdateGroup.class})
	private String name;
	/**
	 * 品牌logo地址
	 */
	@NotBlank(groups = {AddGroup.class})
	@URL(message = "logo必须是一个合法的url地址",groups = {AddGroup.class, UpdateGroup.class})
	private String logo;
	/**
	 * 介绍
	 */
	private String descript;
	/**
	 * 显示状态[0-不显示;1-显示]
	 */
	@ListValue(vals={0,1}, groups = {AddGroup.class})
	private Integer showStatus;
	/**
	 * 检索首字母
	 */
	@NotEmpty(groups = {AddGroup.class})
	@Pattern(regexp = "/^[a-zA-Z]$/",message = "检索首字母必须是一个字母",groups = {AddGroup.class, UpdateGroup.class})
	private String firstLetter;
	/**
	 * 排序
	 */
	@NotNull(groups = {AddGroup.class})
	@Min(value = 0, message = "排序必须大于等于0",groups = {AddGroup.class, UpdateGroup.class})
	private Integer sort;

}

出现的错误 启动gulimallproduct之后测试输出的showStatus是乱码

解决办法

image-20210712095814022

image-20210712095937340

image-20210712095904578

image-20210712095741907

image-20210712095700612

image-20210712095612861

然后重启IDEA才会生效

image-20210712100022054

看某一个类的实现是在这个类上按快捷键是ctrl + h
检验前端时出现的错误 是后端正则表达式的错误

image-20210712211445558

修改正则表达式

image-20210712211604403

gulimall.product.entity

BrandEntity.java

package com.doudou.gulimall.product.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;

import com.doudou.common.valid.AddGroup;
import com.doudou.common.valid.ListValue;
import com.doudou.common.valid.UpdateGroup;
import lombok.Data;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;


/**
 * 品牌
 *
 * @author doudoutj111

 * @date 2021-06-19 17:24:02
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@NotNull(message = "修改必须指定品牌id", groups = {UpdateGroup.class})
	@Null(message = "新增不能指定id", groups = {AddGroup.class})
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 */
	@NotBlank(message = "品牌名必须提交", groups = {AddGroup.class, UpdateGroup.class})
	private String name;
	/**
	 * 品牌logo地址
	 */
	@NotBlank(groups = {AddGroup.class})
	@URL(message = "logo必须是一个合法的url地址",groups = {AddGroup.class, UpdateGroup.class})
	private String logo;
	/**
	 * 介绍
	 */
	private String descript;
	/**
	 * 显示状态[0-不显示;1-显示]
	 */
	@ListValue(vals={0,1}, groups = {AddGroup.class})
	private Integer showStatus;
	/**
	 * 检索首字母
	 */
	@NotEmpty(groups = {AddGroup.class})
	@Pattern(regexp = "^[a-zA-Z]$",message = "检索首字母必须是一个字母",groups = {AddGroup.class, UpdateGroup.class})
	private String firstLetter;
	/**
	 * 排序
	 */
	@NotNull(groups = {AddGroup.class})
	@Min(value = 0, message = "排序必须大于等于0",groups = {AddGroup.class, UpdateGroup.class})
	private Integer sort;

}

image-20210712211820501

状态的检验

点击前端的显示状态出现的问题

{"msg":"参数格式校验失败","code":10001,"data":{"name":"品牌名必须提交"}}

image-20210712212026363

在gulimall-common valid 新建一个接口

image-20210712213352797

gulimall.product.controller

BrandController.java 中添加一个修改状态

package com.doudou.gulimall.product.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

//import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.doudou.common.valid.AddGroup;
import com.doudou.common.valid.UpdateGroup;
import com.doudou.common.valid.UpdateStatusGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.doudou.gulimall.product.entity.BrandEntity;
import com.doudou.gulimall.product.service.BrandService;
import com.doudou.common.utils.PageUtils;
import com.doudou.common.utils.R;

import javax.validation.Valid;


/**
 * 品牌
 *
 * @author doudoutj111
 *
 * @date 2021-06-19 19:40:52
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("product:brand:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
   // @RequiresPermissions("product:brand:info")
    public R info(@PathVariable("brandId") Long brandId){
		BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
  //  @RequiresPermissions("product:brand:save")
    public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand/*, BindingResult result*/){
//        if(result.hasErrors()){
//            Map<String, String> map = new HashMap<>();
//            result.getFieldErrors().forEach((item)->{
//                //FieldError获取到错误信息
//                String message = item.getDefaultMessage();
//                //获取错误属性的名字
//                String field = item.getField();
//                map.put(field, message);
//
//
//
//            });
//            return  R.error(400,"提交的数据不合法").put("data", map);
//
//        }else{
//            brandService.save(brand);
//        }
        brandService.save(brand);


        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
  //  @RequiresPermissions("product:brand:update")
    public R update(@Validated(UpdateGroup.class) @RequestBody BrandEntity brand){
		brandService.updateById(brand);

        return R.ok();
    }

    /**
     * 修改状态
     */
    @RequestMapping("/update/status")
    //  @RequiresPermissions("product:brand:update")
    public R updateStatus(@Validated(UpdateStatusGroup.class) @RequestBody BrandEntity brand){
        brandService.updateById(brand);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
 //   @RequiresPermissions("product:brand:delete")
    public R delete(@RequestBody Long[] brandIds){
		brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }

}

gulimall.product.entity

BrandEntity.java

package com.doudou.gulimall.product.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;

import com.doudou.common.valid.AddGroup;
import com.doudou.common.valid.ListValue;
import com.doudou.common.valid.UpdateGroup;
import com.doudou.common.valid.UpdateStatusGroup;
import lombok.Data;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;


/**
 * 品牌
 *
 * @author doudoutj111

 * @date 2021-06-19 17:24:02
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@NotNull(message = "修改必须指定品牌id", groups = {UpdateGroup.class})
	@Null(message = "新增不能指定id", groups = {AddGroup.class})
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 */
	@NotBlank(message = "品牌名必须提交", groups = {AddGroup.class, UpdateGroup.class})
	private String name;
	/**
	 * 品牌logo地址
	 */
	@NotBlank(groups = {AddGroup.class})
	@URL(message = "logo必须是一个合法的url地址",groups = {AddGroup.class<

以上是关于第185天学习打卡(项目 谷粒商城27 JSR303自定义校验注解 SPU SKU 属性分组效果前端组件抽取 父子组件交互)的主要内容,如果未能解决你的问题,请参考以下文章

第188天学习打卡(项目 谷粒商城30 规格参数新增与VO 规格参数列表)

第198天学习打卡(谷粒商城 项目 排错)

第160天学习打卡(项目 谷粒商城 2)

第196天学习打卡(项目 谷粒商城38 商品新增vo抽取)

第189天学习打卡(项目 谷粒商城31 平台属性规格修改 )

第192天学习打卡(项目 谷粒商城 34 新增分组和属性关联)