1. Reference code download

Download the code branch dev-feature-yuhl

2. Create custom annotations

In the Module: SCRM – common in the package: org.springblade.com mon. Valid. The annotation comments: ListValue

Description: ListValueConstraintValidator. The class notes for this validator

package org.springblade.common.valid.annotation;


import org.springblade.common.valid.validator.ListValueConstraintValidator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/** * custom annotations */
@Documented
@Constraint(validatedBy = { ListValueConstraintValidator.class})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
public @interface ListValue {
    String message(a) default "{com.scrm.common.valid.ListValue.message}"; Class
      [] groups() default {}; Class
      [] payload() default {}; int[] vals() default {}; }Copy the code

3. Create a prompt message

In the Module: SCRM – common path: SCRM – common/SRC/main/resources/ValidationMessages properties

com.scrm.common.valid.ListValue.message=\u5FC5\u987B\u63D0\u4EA4\u6307\u5B9A\u7684\u503C
com.scrm.common.valid.ConstantValue.message=\u987B\u63D0\u4EA4\u5F20\u4E09
Copy the code

4. Create a validator

In the Module: SCRM – common path: org.springblade.com mon. Valid. The validator. ListValueConstraintValidator

package org.springblade.common.valid.validator;

import org.springblade.common.valid.annotation.ListValue;

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

/** * validator */
public class ListValueConstraintValidator implements ConstraintValidator<ListValue.Integer> {

    private Set<Integer> set = new HashSet<>();
    /** * Initialization method */

    @Override
    public void initialize(ListValue constraintAnnotation) {

        int[] vals = constraintAnnotation.vals();
        for (intval : vals) { set.add(val); }}// Check whether the verification is successful

    / * * * *@paramValue Specifies the value to be verified *@param context
     * @return* /
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {

        returnset.contains(value); }}Copy the code

5. Unified exception handling

In the Module: SCRM – member path: com. SCRM. Member. Exception. MemberExceptionControllerAdvice

package com.scrm.member.exception;


import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.IResultCode;
import org.springblade.core.tool.api.R;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

/** * handle all exceptions */
@Slf4j
@RestControllerAdvice(basePackages = "com.scrm.member.controller") // contains @responseBody and @controllerAdvice
public class MemberExceptionControllerAdvice extends ServiceException {


	public MemberExceptionControllerAdvice(String message) {
		super(message);
	}

	public MemberExceptionControllerAdvice(IResultCode resultCode) {
		super(resultCode);
	}

	public MemberExceptionControllerAdvice(IResultCode resultCode, Throwable cause) {
		super(resultCode, cause);
	}

	/ * * * the true MethodArgumentNotValidException abnormal processing logic *@param e
     * @return* /
    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("Data verification error {}, exception type: {}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        // fielderor.getField () : Can retrieve the specific field problem
        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
		return R.fail("Data verification error" + e.getMessage() + ", exception type: + e.getClass() + ")");
    }
    /** * exception handling logic *@param e
     * @return* /
    @ExceptionHandler(value= Exception.class)
    public R handleVaildException(Exception e){
        log.error("Data verification error {}, exception type: {}",e.getMessage(),e.getClass());
		return R.fail("System unknown exception"); }}Copy the code

6. Create a Group

In the Module: SCRM – common path: org.springblade.com mon. Valid. Group

7. Entity class

In the Module: SCRM – member – API path: com. SCRM. Member. The entity. The Brand

package com.scrm.member.entity;


import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import org.hibernate.validator.constraints.URL;
import org.springblade.common.valid.annotation.ConstantValue;
import org.springblade.common.valid.group.AddGroup;
import org.springblade.common.valid.annotation.ListValue;
import org.springblade.common.valid.group.UpdateGroup;
import org.springblade.common.valid.group.UpdateStatusGroup;
import org.springblade.common.valid.group.UpdateZhangsanGroup;

import javax.validation.constraints.*;
import java.io.Serializable;

/** * brand **@author yuhl
 * @email [email protected]
 * @dateThe 2020-09-04 14:12:07 * /
@Data
@TableName("brand")
public class Brand implements Serializable {
	private static final long serialVersionUID = 1L;

	/** * brand id ** /
	@notnull (message = "modify must specify brand id",groups = {updategroup.class})
	@null (message = "new can't specify id",groups = {addgroup.class})
	@TableId
	private Long brandId;
	/** ** brand name */
	@ NotBlank (message = "brand name must submit", groups = {UpdateGroup. Class, AddGroup class})
	private String name;
	/** * brand logo address */
	@ URL (message = "logo must be a URL," groups = {UpdateGroup. Class, AddGroup class})
	@NotBlank(groups = AddGroup.class)
	private String logo;
	/** * introduction */
	private String descript;
	/** * Display status [0- no display; 1- display] */
//	@Pattern()
	@listvalue (vals = {0,1},groups = {addgroup.class, updatestatusgroup.class})
	@NotNull(groups = {AddGroup.class,UpdateStatusGroup.class})
	private Integer showStatus;
	/** * retrieves the first letter *@PatternCustom re */
	^ @ the Pattern (regexp = "$" [a zA - Z], message =" retrieving lost letters must be a letter ", groups = {UpdateGroup. Class, AddGroup class})
	@NotEmpty(groups = {AddGroup.class})
	private String firstLetter;
	/** ** sort */
	@ Min (value = 0, message = "order" must be greater than or equal to 0, groups = {UpdateGroup. Class, AddGroup class})
	@NotNull(groups = {AddGroup.class})
	private Integer sort;

	@constantValue (value = "group ",groups = {addGroup. class, updatestatusgroup.class})
	@NotNull(groups = {UpdateZhangsanGroup.class})
	@TableField(exist = false)
	private String other;
}
Copy the code

8. The controller used

In the Module: SCRM – member path: com. SCRM. Member. Controller. BrandController

package com.scrm.member.controller;

import com.scrm.member.entity.Brand;
import org.springblade.common.valid.group.AddGroup;
import org.springblade.common.valid.group.UpdateGroup;
import org.springblade.common.valid.group.UpdateStatusGroup;
import org.springblade.common.valid.group.UpdateZhangsanGroup;
import org.springblade.core.tool.api.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** * brand **@author yuhl
 * @email [email protected]
 * @dateThe 2020-09-04 14:48:33 * /
@RestController
@RequestMapping("brand")
public class BrandController {
     /** * info */
    @RequestMapping("/infos")
    public R info(@RequestParam("brandIds") List<Long> brandIds){

        //List<Brand> brands = brandService.getBrandByIds(brandIds);

		return R.success("Success");
    }

    /** * Save * use BindingAdvise to sense exceptions instead of encapsulating exceptions with BindingResult */
    @RequestMapping("/save1")
    public R save1(@Valid @RequestBody Brand brand, BindingResult result){
        if(result.hasErrors()){
            Map<String,String> map = new HashMap();
            //1 get the error result of validation
            result.getFieldErrors().forEach((item)->{
                //FieldError gets an error message
                String message = item.getDefaultMessage();
                // Get the name of the wrong attribute
                String field = item.getField();
                map.put(field,message);
            });
			return R.fail("The data submitted is illegal.");
        } else {
            //brandService.save(brand);
        }
        //brandService.save(brand);
        return R.success("Success!);
    }

    /** * save */
    @RequestMapping("/save")
    public R save(@Validated({AddGroup.class})@RequestBody Brand brand){
        //brandService.save(brand);
		return R.success("Success!);
    }

    @RequestMapping("/mysave")
    public R mysave(@Valid @RequestBody Brand brand){
		//brandService.save(brand);
		return R.success("Success!);
    }

    /** * modify */
    @RequestMapping("/update")
    public R update(@Validated(UpdateGroup.class) @RequestBody Brand brand){
        //brandService.updateDetail(brand);
		return R.success("Success!);
    }

	/**
	 * 修改
	 */
	@RequestMapping("/updatezhangsan")
	//@RequiresPermissions("product:brand:update")
	public R updatezhangsan(@Validated(UpdateZhangsanGroup.class) @RequestBody Brand brand){
		//brandService.updateDetail(brand);
		return R.success("Success!);
	}

    /** * Change the status */
    @RequestMapping("/update/status")
    public R updateStatus(@Validated(UpdateStatusGroup.class) @RequestBody Brand brand){
        //brandService.updateById(brand);

		return R.success("Success!);
    }

    /** * delete */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] brandIds){
		//brandService.removeByIds(Arrays.asList(brandIds));
		return R.success("Success!); }}Copy the code