参数校验框架:spring validation(使用预定义的注解完成参数校验)
- 引入Spring Validation起步依赖
~~~xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2. 在参数前面加Pattern注解
```kotlin
public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password)
- 在Contorller类上添加@Validation注解(@Validated)
- 因为利用校验函数,所以返回值不合法,要创建一个异常处理类实现,返回值的可读性
package com.di.bigevent.exception;
import com.di.bigevent.pojo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public Result handlerException(Exception e){
e.printStackTrace();
return Result.error(StringUtils.hasLength(e.getMessage())? e.getMessage() : "操作失败");
}
}
标签:请求,Pattern,校验,springframework,2024,Result,org,import
From: https://www.cnblogs.com/muzhaodi/p/18047929