参数校验学习笔记

springboot和dubbo项目注解进行参数校验

springboot项目注解进行参数校验

  • 参数是bean类型对象,在定义类时在字段上使用@NotNull等注解进行标记,然后在使用该对象作为参数的方法入口处使用@Valid来进行验证,如果controller类上加了@Validated注解,也要在参数前面加上@Validated或者@Valid注解,不然也不会起效;如下所示:
java 复制代码
// bean对象定义
public class UserReq {
	@NotNull
	private String username;
	@NotBlank
	private String password;
}
// 在controller层使用参数校验
@RestController
@RequestMapping("/user")
public class UserControler {
	
	@PostMapping("/v1")
	// 这里也可以用@Validated替换@Valid注解
	// @Validated是springboot框架在@Valid基础上实现的注解
	// @Valid是java官方的注解
	public String login(@Valid @RequestBody UserReq userReq) {
		reutrn "";
	}
}
  • 参数是基本类型;一定要在类上加上@Validated才生效,否则在参数前面加@Validated或@Valid都不会生效;@Valid在类上不生效,不能放在类上
java 复制代码
// 在controller层使用参数校验
@RestController
@RequestMapping("/user")
@Validated
public class UserControler {
	
	@PostMapping("/v1")
	// 
	public String login(@NotNull String ss) {
		reutrn "";
	}
}

dubbo接口的注解参数校验

  • bean类型的参数校验,与springboot类似,先要在bean类型的参数上使用@NotNull等进行标记,但是不需要@Valid就可以直接生效,但必须在暴露接口的配置中开启验证;如下所示:
java 复制代码
public class UserReq{
	@NotNull
	private String name;
	@NotNull
	private String password;
}

public interface UserService {
	void save(UserReq user);
}

@Service
public class UserServiceImpl implements UserService {
	// 不需要加@Valid之类
	@Override
	public void save(UserReq user) {
		System.out.println("nihao");
	}

}

// Rpc.xml配置文件 一定要加上validation = true
<dubbo:service interface="com.xxx.service.UserService" ref="userServiceImpl" validation="true" />
  • 单个参数校验:需要将参数校验写在接口而不是实现类上,这是与Springboot的区别;如下所示:
java 复制代码
public interface UserService {
	void get(@NotNull(message = "id不能为空") Long id);
}

@Service
public class UserServiceImpl implements UserService {
	// 不需要加@Valid之类
	@Override
	public void get(Long id) {
		System.out.println("nihao");
	}
}

// Rpc.xml配置文件 一定要加上validation = true
<dubbo:service interface="com.xxx.service.UserService" ref="userServiceImpl" validation="true" />

dubbo接口检验参考:
单个参数校验
参数校验

相关推荐
Nyarlathotep01135 小时前
SpringBoot Starter的用法以及原理
java·spring boot
dkbnull1 天前
深入理解Spring两大特性:IoC和AOP
spring boot
洋洋技术笔记1 天前
Spring Boot条件注解详解
java·spring boot
洋洋技术笔记2 天前
Spring Boot配置管理最佳实践
spring boot
用户8307196840823 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
大道至简Edward3 天前
Spring Boot 2.7 + JDK 8 升级到 Spring Boot 3.x + JDK 17 完整指南
spring boot·后端
洋洋技术笔记3 天前
Spring Boot启动流程解析
spring boot·后端
怒放吧德德4 天前
Spring Boot 实战:RSA+AES 接口全链路加解密(防篡改 / 防重放)
java·spring boot·后端
李慕婉学姐4 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
QQ5110082854 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php