用spring的@Validated注解和org.hibernate.validator.constraints.*的一些注解在后台完成数据校验
这个demo主要是让spring的@Validated注解和hibernate支持JSR数据校验的一些注解结合起来,完成数据校验。这个demo用的是springboot。
首先domain对象Foo的代码如下:
package com.entity; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.Min; public class Foo { @NotBlank(message = "此name不能为空") private String name; @Min(value = 18,message = "此age最小为18") private Integer age; @Email(message = "邮箱格式错误") private String email; 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; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
其次controller层的代码如下:
package com.validation; import com.entity.Bar; import com.entity.BarValidator; import com.entity.Foo; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; @RestController public class FooController { @RequestMapping("/fooTest") public String foo(@Valid Foo foo, BindingResult result){ if(result.hasErrors()){ List<ObjectError> allErrors = result.getAllErrors(); for(ObjectError objectError :allErrors){ String defaultMessage = objectError.getDefaultMessage(); System.out.println("defalutMessage="+defaultMessage); } System.out.println("allErrors="+allErrors.toArray()); return "failed"; } return "success"; } }
启动spring boot的代码如下:
package com.validation; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }