日期:2014-05-16 浏览次数:20334 次
package json; import javax.validation.constraints.Digits; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Email; import constraints.IsDate; public class JSONCustomer { @NotEmpty private String name; @NotEmpty private String addr; @NotEmpty @IsDate(format="yyyy-MM-dd") private String birthday; @NotEmpty private String hukou; @Email private String email; @Pattern(regexp="(((\\w+)\\.)+(\\w+))?") private String url; @Digits(integer = 3, fraction = 0) @Min(value = 100) @Max(value = 230) private String height; //setter, getter略 }
package controller; import java.lang.reflect.InvocationTargetException; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.apache.commons.beanutils.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import json.JSONCustomer; import json.JSONResponse; import vo.Customer; @Controller @RequestMapping("/customerInfo") public class CustomerInfoController extends JSONController { @Autowired public CustomerInfoController(Validator validator) { super(validator); } @RequestMapping(value = "/new", method = RequestMethod.POST) @ResponseBody public JSONResponse newCustomer(@RequestBody JSONCustomer jsoncustomer) throws IllegalAccessException, InvocationTargetException { Set<ConstraintViolation<JSONCustomer>> failures = validator.validate(jsoncustomer); if (failures.isEmpty()) { //校验通过 Customer customer = new Customer(); //将接收的全String属性对象转成vo BeanUtils.copyProperties(jsoncustomer, customer); return successed(jsoncustomer); } else { //校验失败 return failed(failures); } } }
package constraints; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Target( { METHO