一.
@Valid作用:限制或校验某些参数:
简单写一个添加student到mysql:
Student类:
package com.example.test;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Entity
@Table(name="t_student")
public class Student {
@Id
@GeneratedValue
private Integer id;
@NotEmpty(message="姓名不能为空!")
@Column(length=50)
private String name;
@NotNull(message="年龄不能为空!")
@Min(value=18,message="年龄必须大于18岁!")
@Column(length=50)
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
然后写一个StudentControlller类:
package com.example.test;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.service.StudentService;
@RestController
@RequestMapping("/student")
public class StudentController {
@Resource
private StudentService service;
@ResponseBody
@PostMapping("/add")
public String addstudent(@Valid Student student,BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return bindingResult.getFieldError().getDefaultMessage();
}else {
service.add(student);
return "添加成功!";
}
}
}
其余部分和之前增删改查代码相仿,不再阐述。
测试localhost:8888/student/add即可