spring mvc中的条件验证

时间:2015-04-13 14:15:33

标签: spring validation spring-mvc spring-4

现在我有以下控制器方法签名:

@ResponseBody
    @RequestMapping(value = "/member/createCompany/addParams", method = RequestMethod.POST)
    public ResponseEntity setCompanyParams(
            @RequestParam("companyName") String companyName,
            @RequestParam("email") String email,               
            HttpSession session, Principal principal) throws Exception {...}

我需要为输入参数添加验证。 现在我要创建这样的对象:

class MyDto{
    @NotEmpty            
    String companyName;
    @Email // should be checked only if principal == null
    String email;   
}

我会写这样的东西:

@ResponseBody
@RequestMapping(value = "/member/createCompany/addParams", method = RequestMethod.POST)
public ResponseEntity setCompanyParams( MyDto myDto, Principal principal) {
    if(principal == null){
        validateOnlyCompanyName(); 
    }else{
         validateAllFields();
    }
    //add data to model
    //return view with validation errors if exists.
}
你可以帮助实现我的期望吗?

1 个答案:

答案 0 :(得分:0)

这不是Spring MVC验证的工作方式。验证器将验证所有字段,并将其结果放在BindingResult对象中。

但是,当principal为null时,由你来做特殊处理,在这种情况下看作是字段companyName的验证:

@ResponseBody
@RequestMapping(value = "/member/createCompany/addParams", method = RequestMethod.POST)
public ResponseEntity setCompanyParams(@ModelAttribute MyDto myDto, BindingResult result,
        Principal principal) {
    if(principal == null){
        if (result.hasFieldErrors("companyName")) {
            // ... process errors on companyName Fields
        } 
    }else{
         if (result.hasErrors()) { // test any error
             // ... process any field error
         }
    }
    //add data to model
    //return view with validation errors if exists.
}