spring参数校验之validation的使用

spring参数校验之validation的使用

1、在代码编写中,经常会遇到参数校验,包括:必填、正则,取值范围限制等
话不多说,上代码

@RestController
@RequestMapping("/valida")
public class ValidaZsgController{
	
    @RequestMapping("/validaParam")
    public String validaParam(@Validated @RequestBody ValidaUser user, BindingResult result) throws Exception{

        if (result.hasFieldErrors()) {
            String errorInfo = ValidationUtils.operateBindingResult(result);

			# 输出校验参数信息
            System.out.println(errorInfo);
        }
        return "success";
    }
}

2、参数对象


import com.alibaba.fastjson.JSONObject;
import com.example.demo.utils.CheckUrl;
import com.example.demo.utils.MyCheck;
import lombok.Data;

import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;

@Data
public class ValidaUser{


    private final String reg = "^((http|https)://)[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]";


	# 整型,最大值与最小值限制
    @Min(value = 0, message = "参数大小不可小于0")
    @Max(value = 2, message = "参数大小不可大于2")
    private int status;
    
    # String 类型限制指定参数(参数中只能是,‘张三’、’李四‘,或者'123456788')
	@Pattern(regexp = "张三|李四|123456788", message = "用户名称非指定")
    private String name;

	# 手机号(中国)校验
	@Pattern(regexp = "^[1][3,4,5,6,7,8,9][0-9]{9}$", message = "手机号不正确")
    private String phone;

	# 集合非空检验
	@Size(min = 1, message = "最大长度不能超过3")
    @NotNull(message = "变量填写不能为空,请先填写变量!")
    private List list;

	# 邮箱验证
    @Email(message = "api.user.error")
    private String mail;
	
	# String必填校验
	@NotBlank(message = "nickName不可输入为空")
	private String nickName;

	# 网址校验  此校验参数不可为 “”, 否则校验参数不通过
	@Pattern(regexp = reg, message = "网址不对")
	private String contractCallBackUrl;


	# 嵌套对象的校验只能使用@Valid或者@Validated
	@Valid  
    @NotNull(message = "validaInfo不可为空")
    private ValidaInfo validaInfo;

    @NotNull(message = "type不可为空")
    @Min(value = 0, message = "type超限")
    @Max(value = 2, message = "type超限")
    private Integer type;


	# 有参构造方法   可根据需要,进行参数校验
  public ValidaUser(Short status, String name, String address, String phone, int age, List list, String mail) {
        this.status = status;
        this.name = name;
        this.address = address;
        this.phone = phone;
        this.age = age;
        this.list = list;
        this.mail = mail;
    }
}


import javax.validation.constraints.NotBlank;

public class ValidaInfo {

    @NotBlank(message = "templateId不可为空")
    private String templateId;

    public String getTemplateId() {
        return templateId;
    }

    public void setTemplateId(String templateId) {
        this.templateId = templateId;
    }
}

3、单元测试类

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
@AutoConfigureMockMvc
public class ValidaControllerTest {

@Autowired
    private MockMvc mockMvc;

    @Test
    public void validaParam(){
        List list = Arrays.asList("1212", "1212", "1212", "1212", "1212", "1212", "1212", "1212", "1212", "1212", "1212", "1212");
        
        ValidaUser validaUser = new ValidaUser((short) 3, "张三", "北京市", "13405608901", 11, list, "[email protected]");
        try {
            mockMvc.perform(post("/valida/validaParam")//请求地址使用post方式请求
                            .content(JSON.toJSONString(validaUser))
                            .contentType(MediaType.APPLICATION_JSON_VALUE))//媒体类型为JSON
//                    .andExpect(status().isOk());//返回状态为200
                    .andDo(print());// 打印请求和响应的详情

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

4、结果输出如下
spring参数校验之validation的使用_第1张图片

你可能感兴趣的:(spring,java,后端)