Spring3 MVC的最佳实践和理解(8)

阅读更多

 

个人学习参考所用,勿喷! 

 

8.Bean的注解式校验

为了使用JSR-303的注解式校验,首先必须要修饰一个Bean:

public class Member {

    // JSR-303 validation annotations
    @NotNull
    @Size(min=2)
    private String name;
    @NotNull
    @Size(min = 9, max = 14)
    private String phone;
    @Pattern(regexp=".+@.+\\.[a-z]+")
    private String email;
	
	...
}

 

 然后在控制器类中实施这些校验:

@Controller
@RequestMapping("/member/*")
@SessionAttributes("guests")
public class MemberController {
    // JSR-303 validator
    private static Validator validator;
    private MemberService memberService;

    @Autowired
    public MemberController(MemberService memberService) {
        this.memberService = memberService;

        // Initialize JSR-303 bean validation
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.getValidator();
    }

    ...

    @RequestMapping(method = RequestMethod.POST)
    public String submitForm(@ModelAttribute("member")
    Member member, BindingResult result, Model model) {
        // Get JSR-303 errors ( See domain Member class for annotations validation) 
        Set> violations = validator.validate(member);

        for (ConstraintViolation violation : violations) {
            String propertyPath = violation.getPropertyPath().toString();
            String message = violation.getMessage();
            result.addError(new FieldError("member", propertyPath, "Invalid " + propertyPath + "(" + message + ")"));
        }

        if (!result.hasErrors()) {
            ...
        } else {
            ...
        }
    }
}

 

 在这里我们是手动的在构造器中完成了validator的初始化。其实也可以让Spring来注入,Spring的高级注入方式有工厂方式的注入。要使用上面的校验需要添加如下的jar支持:


	javax.validation
	validation-api
	1.0.0.GA
	jar
	compile


	org.hibernate
	hibernate-validator
	4.3.0.Beta1
	jar
	compile

 

 

 

参考:

juyon的blog:《spring3 MVC国际化支持之中文乱码

Gary Mark等的书籍:《Spring Recipes》2ed

 

你可能感兴趣的:(Spring3,MVC,最佳实践,Spring注解式校验,JSR-303,MVC)