当前位置:网站首页>【项目实训】校验注解
【项目实训】校验注解
2022-06-12 01:13:00 【par_ser】
在web项目中常常要做参数校验,如果把参数校验都和业务代码混杂在一起,会使代码显得臃肿,降低代码的可读性。
参数校验是一个这么普遍的需求,于是JCP组织定义了一个标准(JSR303)来规范化这个任务操作,那就是Java Validation API。但没有提供实现,而hibernate validation是对这个规范的实现,并增加了校验注解如@Email、@Length等。Spring Validation是对hibernate validation的二次封装,用于支持spring mvc参数自动校验。
JSR303支持的校验注解如下:

hibernate validation 提供的扩展注解如下:

引入依赖
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.1.Final</version>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>上述两种皆可
代码
RequestBody参数校验
通常POST、PUT请求会使用requestBody传递参数,在controller层我们用对象接收参数。那么只要该对象实现了getter/setter方法,springmvc会为我们自动绑定对象。只要在对象加上@Validated或者@Valid注解就能实现自动参数校验。校验失败时会抛出MethodArgumentNotValidException异常,Spring默认会将其转为http 400(Bad Request)响应。
@ApiOperation(value="职能科室暂存事件处理表项",notes = "职能科室暂存事件处理表项")
@PostMapping("/temporarySave")
@LogAnnotation(operation = "职能科室暂存事件处理表项")
public ResponseResult temporarySave(HttpServletRequest request, @RequestBody @Validated({TemporarilySave.class}) FunctionalDepartmentChartDTO functionalDepartmentChartDTO){
adverseEventReportFunctionalDepartmentRelationService.temporarySave(request,functionalDepartmentChartDTO);
return ResponseResult.okResult();
}RequestParam/PathVariable参数校验
GET请求一般会使用requestParam/PathVariable传参。在这种情况下,必须在Controller类上标注@Validated注解,并在入参上声明约束注解(如@Min等)。如果校验失败,会抛出ConstraintViolationException异常。
@RestController
@RequestMapping("/patientInfo")
@Validated
public class PatientInfoController {
@Autowired
private IPatientInfoService patientInfoService;
@ApiOperation(value = "根据住院号,门诊号或就诊卡号来查询病人信息",notes = "method:0是住院,1是门诊,2是就诊卡")
@GetMapping("/{key}/{method}")
@LogAnnotation(operation = "根据住院号,门诊号或就诊卡号来查询病人信息")
public ResponseResult get(@PathVariable("key") String key , @PathVariable("method") @Range(min = 0,max = 2,message = "method需要在0和2之间") Integer method){
return ResponseResult.okResult(patientInfoService.get(key,method));
}
}PS:针对上述所说的MethodArgumentNotValidException和ConstraintViolationException,我们可按照之前所讲的“统一异常处理”,也做异常拦截,进行统一的处理。
分组校验
同个类的对象,可能作为不同接口的参数,在校验时遵循不同的规则,于是我们需要分组校验来加以区分。具体地,类似下方代码,在校验注解中注明其适用的组别,在@Valided注解处注明要使用的组别(如@Validated({Persist.class})
/**
* 产品名称
*/
@NotBlank(message = "产品名称不能为空", groups = {Persist.class})
private String productName;
/**
* 注册证号
*/
@NotBlank(message = "注册证号不能为空", groups = {Persist.class})
private String registrationNum;边栏推荐
- How to guarantee industrial control safety: system reinforcement
- Explain asynchronous tasks in detail: the task of function calculation triggers de duplication
- Article 7: Design of multifunctional intelligent trunk following control system | undergraduate graduation project - [module device selection, list and data]
- Lambda intermediate operation skip
- MS-HGAT: 基于记忆增强序列超图注意力网络的信息扩散预测
- Sharing of Manta network parallel chain solutions by Hufu Research Institute
- C dynamically calls the static library generated by go
- Equipment encryption of industrial control security
- How much is the child's critical illness insurance coverage appropriate? Which product is better now
- Crawler case 05 - parsing websites using XPath
猜你喜欢

The CSV used for JMeter performance test is bullshit

一文get,最容易碰上的接口自动化测试问题汇总

flowable 工作流

Comparison of OpenCV basic codes of ros2 foxy~galactic~humble

jmeter 性能测试用 csv,这个坑有些扯蛋

Argodb 3.2 of star ring technology was officially released to comprehensively upgrade ease of use, performance and security

Building circuits on glass

Matlab 基础应用02 wind 股票数据介绍和使用案例:

Crawler case 05 - parsing websites using XPath

Before applying data warehouse ODBC, you need to understand these problems first
随机推荐
验证码是自动化的天敌?看看阿里P7大神是怎么解决的
人们对于产业互联网的这样一种认识的转变,并不是一蹴而就的
Article 4: Design of multifunctional intelligent trunk following control system | undergraduate graduation project - [data search skills + reference resource integration]
基于.NetCore开发博客项目 StarBlog - (11) 实现访问统计
河南中创|从云到边,边缘计算如何赋能数据中心
C language structure - learning 27
C language string and pointer - learning 25
Comparison of OpenCV basic codes of ros2 foxy~galactic~humble
Industry competition analysis and investment scale research report of global and Chinese micro potato industry 2022-2028
Virtual human appears on the stage of the Winter Olympic Games, connecting elements of the meta universe
Websocket server practice
Article 8: Design of multi-functional intelligent trunk following control system | undergraduate graduation project - [reply and Q & a record of design completion]
Global and Chinese medical styrene block copolymer industry prospect research and investment planning proposal report 2022-2028
Lambda intermediate operation flatmap
[path of system analysts] summary of real problems of system analysts over the years
About MySQL password modification failure
Jmeter接口测试之常用断言
Introduction to semantic vector retrieval
2022 edition of global and Chinese sodium hydrosulfide market in-depth investigation and prospect Trend Forecast Report
Flowable workflow