A, Validator What is the role?
-
In development often need to write some field validation code, such as non-empty field, field length limit, the mailbox format validation, etc.
-
Prevent attacks! We separated the front and rear ends, we only provide the back-end data interface, if people want to break us, others can skip the tip!
1.1 Scene
FIG verification on only the front end of the verification. It will increase the back-end normative data, but others you can skip this verification front-end!
Use Postman can skip validation front.
So we need to do a verification of the data in the back-end
1.2 validate the use of
- Add Hibernate-Validator-dependent. If the current project and there is springboot web dependent, you do not need to reference any dependent, because springboot-starter-web package already contains a Hibernate-Validator-dependent
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.7.Final</version>
</dependency>
- Plus corresponding annotations on properties of the class, set, get lombok method uses frame, @ apiModelProperty annotation is dependent swagger2
- Add @RequestBody and @Valid annotation on the back-end post method
Only add @Valid notes, written on the class notes before they can take effect.
- Check validator annotation is in effect
From the above chart, check annotations take effect, but will throw an exception. So it should be an exception to this process
1.3 validator common comment
annotation | DEFINITIONS |
---|---|
@NotNull | The annotated element must not be null elements can be any value |
@NotBlank | Labeled string can not be null or empty string in the string tag can |
@NotEmpty | The labeled set can not be null or empty set markers on the set |
@Null | The annotated element must be null |
@AssertTrue | The element being annotated must be true |
@AssertFalse | The element being annotated must be false |
@Min(value) | Annotated element must be a number whose value must be greater than the specified minimum |
@Max(value) | Annotated element must be a number which must be less than the maximum value equal to the specified |
@DecimalMin(value) | Annotated element must be a number whose value must be greater than the specified minimum |
@Size(max, min) | Note the size of the element must be within the specified range, the element must be set, representing the number of sets |
@Digits (integer, fraction) | Annotated element must be a number whose value must be within an acceptable range |
@Past | The annotated element must be a date in the past |
@Future | The annotated element must be a future date |
The annotated element must be the e-mail address | |
@Length(min=, max=) | Note the size of the string must be within a specified range, must be an array or string, if the array is an array of said length, it said string is a string |
@Range(min=, max=) | Elements must be annotated in the range of appropriate |
@Pattern(regexp = ) | Regular expressions check |
@Valid | Cascade verification objects, i.e., objects in the object property check |
Second, the global exception handling
package com.zxm.aspect;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j // 记录日志的注解 相当于private static final Logger log = LoggerFactory.getLogger(WebLogError.class);
@RestControllerAdvice // 用户拦截Controller抛给用户的异常信息
public class WebLogError {
/**
* 代表用户登录可能过期了
*/
@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<String> authException(){
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("你的登录已经过期,请重新登录");
}
/**
* 参数异常:需要给别人提醒一下
*/
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> paramException(IllegalArgumentException e){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
/**
* 若是运行时,异常,我们的错误信息不能随便泄露给别人
* @param e
* @return
*/
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> runtimeException(RuntimeException e){
log.error("运行异常",e); // 可以帮我们记录在日志文件里面。方便排错
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器正在维修");
}
/**
* shiro 里面没有某种权限的异常
* @return
*/
@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<String> unauthorized(){
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("没有权限访问") ;
}
/**
* shiro 里面没有某种权限的异常
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<String> methodArgumentNotValidException(MethodArgumentNotValidException bindException){
BindingResult bindingResult = bindException.getBindingResult();// bindingResult就是验证错误的结果
System.out.println(bindingResult);
StringBuffer sb = new StringBuffer("数据校验失败,原因是:");
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
for (FieldError fieldError : fieldErrors) {
/**
* fieldError.getField 那个字段
* fieldError.getDefaultMessage 错误原因
*/
sb.append(fieldError.getDefaultMessage()+"!");
}
return ResponseEntity.badRequest().body(sb.toString());
}
}