2011-11-30 52 views
0

我有兩個類(豆)如何驗證在Spring控制器方法兩個或兩個以上豆Hibernate驗證(JSR 303)

public class BeanOne { 
    @Min(1) 
    private Integer idBeanOne; 
    @NotBlank 
    private String nameBeanOne; 
    @NotNull 
    @Min(1) 
    private Integer idOther; 
    // ... Getters and Setters 
} 

public class BeanTwo { 
    @Min(1) 
    private Integer idBeanTwo; 
    @NotBlank 
    private String nameBeanTwo; 
    @NotNull 
    @Min(1) 
    private Integer idOtherTwo; 
    // ... Getters and Setters 
} 

// Method in Controller 
@RequestMapping(value = "/name.html", method = RequestMethod.POST) 
public @ResponseBody 
Map<String, Object> submitInsert(@Valid BeanOne one, 
    @Valid BeanTwo two, BindingResult result) { 

    if (result.hasErrors()) { 
    // Errores 
    } else { 
    // :D 
    } 
} 

的控制器有什麼辦法我可以驗證兩個或更多的豆子?我已成功驗證了單個bean,但是我沒有成功驗證兩個或更多的bean。我怎樣才能做到這一點? 感謝:D 感謝:D

回答

0

經過多次嘗試使用JSR303驗證兩個或多個bean後,來到這個解決方案。

public class BeanOne { 
    @Valid 
    private BeanTwo beanTwo; 
    // other beans to validate 
    @Valid 
    private BeanN beanN; 

    @Min(1) 
    private Integer idBeanOne; 
    @NotBlank 
    private String nameBeanOne; 
    @NotNull 
    @Min(1) 
    private Integer idOther; 
    // ... Getters and Setters 
} 

public class BeanTwo { 
    @Min(1) 
    private Integer idBeanTwo; 
    @NotBlank 
    private String nameBeanTwo; 
    @NotNull 
    @Min(1) 
    private Integer idOtherTwo; 
    // ... Getters and Setters 
} 

//控制器春

@Controller 
public class XController { 

    @Autowired 
    private Validator validator; 

    @RequestMapping(value = "/name.html", method = RequestMethod.POST) 
    public @ResponseBody Map<String, Object> 
    submitInsert(BeanOne beanOne, BeanTwo beanTwo, BindingResult result) { 

    beanOne.setBeanTwo(beanTwo); 
    // beanOne.setBeabN(beanN); 
    validator.validate(beanOne, result); 

    if (result.hasErrors()) { 
     // Errores 
    } else { 
     // :D 
    } 
    } 
    // more code ... 
} 

但現在我有一個問題:(

我有這個文件Messages.properties

typeMismatch.java.lang.Integer = Must specify an integer value. 
typeMismatch.java.lang.Long = Must specify an integer value. 
typeMismatch.java.lang.Float = Must specify a decimal value. 
typeMismatch.java.lang.Double=Must specify a decimal value. 

此文件可以幫助我當一個領域期望一個數字時,以及我們呃輸入文本

這完全適用於第一個bean(BeanOne),但不能嵌套豆(BeanTwo,BeanN)

我希望他們能幫助我:d

感謝

相關問題