.1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.实体类加入注解
@Data
public class Order {
// 必须不为 null, 大小是 10
@NotNull
@Size(min = 10, max = 10)
private String orderId;
// 必须不为空
@NotEmpty
private String customer;
// 必须是一个电子信箱地址
@Email
private String email;
}
3.在接口上加入 @Valid注解
@PostMapping("insertOrder")
public String getbyparam(@RequestBody @Valid Order order){
System.out.println(order.toString());
return "ok";
}
4.通用返回对象R
package com.example.demo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author yaoxinjia
*/
public class R extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
public R() {
put("code", 0);
put("msg", "success");
}
public R setData(Object data){
put("data",data);
return this;
}
public <T> T getData(String key,TypeReference<T> typeReference){
Object data = get(key);
String s = JSON.toJSONString(data);
T t = JSON.parseObject(s, typeReference);
return t;
}
public <T> T getData(TypeReference<T> typeReference){
Object data = get("data");
String s = JSON.toJSONString(data);
T t = JSON.parseObject(s, typeReference);
return t;
}
public static R error() {
return error(500, "未知异常,请联系管理员");
}
public static R error(String msg) {
return error(500, msg);
}
public static R error(int code, String msg) {
R r = new R();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static R ok(String msg) {
R r = new R();
r.put("msg", msg);
return r;
}
public static R ok(Map<String, Object> map) {
R r = new R();
r.putAll(map);
return r;
}
public static R ok() {
return new R();
}
public R put(String key, Object value) {
super.put(key, value);
return this;
}
public Integer getCode(){
return (Integer) this.get("code");
}
}
5.全局统一处理异常
package com.example.demo.exception;
import com.example.demo.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice(basePackages = "com.example.demo.controller")
public class GlobalException {
//JSR303校验异常处理
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R handleValidException(MethodArgumentNotValidException e){
BindingResult bindingResult = e.getBindingResult();
Map<String,String> map=new HashMap<>();
bindingResult.getFieldErrors().forEach(item->{
//获取校验失败自定义的message
String message = item.getDefaultMessage();
//获取校验失败的字段
String name=item.getField();
map.put(name,message);
});
return R.error(500,"数据格式错误").put("data",map);
}
//处理任意类型的异常
@ExceptionHandler(Throwable.class)
public R handleCommonException(Throwable throwable){
return R.error();
}
}