jsr检验,接口对接中常用的校验方式,本文章只作记录,没有详述原理
项目结构:
- controller 里面有两个方法,一个是post方式的校验,一个是get方式的校验
- config 里面是定义的异常拦截机制,一个拦截post,一个拦截get
- vo 里面有两个实体,一个是返回结果的BaseOutput,一个测试用的校验实体
maven 依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>boot</finalName>
</build>
vo pack
public class BaseOutput<T> {
private String code;
private String message;
private boolean flag;
private T data;
public static BaseOutput withSucc(Object data){
BaseOutput out = new BaseOutput();
out.setCode( "200");
out.setFlag(true);
out.setMessage("请求成功");
out.setData(data);
return out;
}
public static BaseOutput withFail(String message){
BaseOutput out = new BaseOutput();
out.setCode( "400");
out.setFlag(false);
out.setMessage(message);
return out;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
public class ValidataEntivy {
@NotNull(message = "name不能为空")
private String name;
@Email
private String email;
private String adress;
@NotNull(message = "性别不能为空")
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
controller
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import boot.vo.BaseOutput;
import boot.vo.ValidataEntivy;
@RestController
public class ValidataController {
@RequestMapping("/validata")
public void validata(@Validated ValidataEntivy validata){
System.out.println(validata.getAdress());
}
@GetMapping("/test")
public BaseOutput test( ValidataEntivy validata){
return BaseOutput.withSucc(null);
}
}
config 自定义异常捕获封装
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import boot.vo.BaseOutput;
@RestControllerAdvice
public class ControllerArgumentExceptionHander {
@ExceptionHandler(MethodArgumentNotValidException.class)
public BaseOutput methArgumentNotValidataException(MethodArgumentNotValidException e){
BaseOutput out = BaseOutput.withSucc(null);
StringBuffer message = new StringBuffer();
BindingResult bindingResult = e.getBindingResult();
if(bindingResult.hasErrors()){
for (ObjectError objectError : bindingResult.getAllErrors()) {
message.append(objectError.getDefaultMessage());
}
out = BaseOutput.withFail(message.toString());
}
return out ;
}
@ExceptionHandler(BindException.class)
public BaseOutput BindException(BindException e){
BaseOutput out = BaseOutput.withSucc(null);
StringBuffer message = new StringBuffer();
BindingResult bindingResult = e.getBindingResult();
if(bindingResult.hasErrors()){
for (ObjectError objectError : bindingResult.getAllErrors()) {
message.append(objectError.getDefaultMessage()+" ");
}
out = BaseOutput.withFail(message.toString());
}
return out ;
}
}
ErrorPageRegistrarConfig 异常页面处理
package com.bitfty.cms.config;
import org.springframework.boot.web.server.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@Configuration
public class ErrorPageRegistrarConfig implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
ErrorPage[] errorPages = new ErrorPage[2];
// HttpStatus.NOT_FOUND跳转404页面
errorPages[0] = new ErrorPage(HttpStatus.NOT_FOUND, "/404");
errorPages[1] = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/exception");
registry.addErrorPages(errorPages);
}
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
//第二种写法:java8 lambda写法
return (factory -> {
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/404");
factory.addErrorPages(errorPage404);
});
}
}
请求结果
- get 请求
post 请求