import com.example.demo.pojo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.Valid;
@Controller
@RequestMapping("/stu")
public class StudentController {
@PostMapping("/addStu")
@ResponseBody
public String addStudent(@Valid Student student){
System.out.println("存储student对象");
System.out.println(student);
return "ok";
}
}
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class Student {
@NotNull(message = "传入的是空值,请传值")
@Min(value = 0,message = "传入学生分数有误,分数在0-100之间")
@Max(value = 100,message = "传入学生分数有误,分数在0-100之间")
private Integer score;
@NotEmpty(message = "传入的是空字符串,请传值")
@NotNull(message = "传入的是空值,请传值")
private String name;
@NotNull(message = "传入的是空值,请传值")
@NotEmpty(message = "传入的是空字符串,请传值")
@Length(min = 11,max = 11,message = "号码有误,长度应为11位")
private String mobile;
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
@Override
public String toString() {
return "Student{" +
"score=" + score +
", name='" + name + '\'' +
", mobile='" + mobile + '\'' +
'}';
}
}
全局统一异常拦截器
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionInterceptor {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public String exceptionHandler(Exception e){
String failMessage=null;
if(e instanceof BindException){
failMessage=((BindException) e).getBindingResult().getFieldError().getDefaultMessage();
}
return failMessage;
}
}


当我们传入的参数有误时,就会被异常拦截器捕获,返回给我们错误信息。

本文介绍了一个使用Spring Boot框架的学生信息控制器,该控制器通过注解实现对学生信息的验证,并利用全局异常拦截器处理验证失败的情况,返回详细的错误信息。
1万+

被折叠的 条评论
为什么被折叠?



