控制器:
package com.awaimai.web; import org.hibernate.validator.constraints.Range; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import java.util.HashMap; import java.util.Map; @Controller @Validated public class kzq { @RequestMapping(value = "/test6") @ResponseBody public String test6(@RequestBody Student student) { String a = student.getFirstName(); String b = student.getLastName(); return a+b; } }
student类:
package com.awaimai.web; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Student { @Size(min = 2,max = 5) private String firstName; @NotNull @Size(min = 2,max = 3) private String lastName; public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLastName() { return lastName; } }
postman访问:
===================================================================
参数校验
控制器:
package com.awaimai.web; import org.hibernate.validator.constraints.Range; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import java.util.HashMap; import java.util.Map; @Controller @Validated public class kzq { @RequestMapping(value = "/test6") @ResponseBody public String test6(@RequestBody @Valid Student student, BindingResult bindingResult) { String a = student.getFirstName(); String b = student.getLastName(); return a+b; } }
student类:
package com.awaimai.web; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Student { @Size(min = 2,max = 5) private String firstName; @NotNull @Size(min = 2,max = 3) private String lastName; public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLastName() { return lastName; } }
postman访问: