2013-10-03 86 views
0

我下面這個問題--->Spring MVC: How to perform validation?Spring MVC的驗證工作不

這裏是我的控制器代碼

@RequestMapping(value = "saveBankDetails.htm", method = RequestMethod.POST) 
    public ModelAndView saveBankDetails(ModelMap model ,@Valid @ModelAttribute("SpringWeb")BankDetails bean, 
      BindingResult result){ 
       System.out.println(result.hasErrors()); 
       System.out.println(bean.getNoOfBankDetails()); 
       System.out.println(bean.getBankDetails().get(0).getNameOfBank()); 
       if(result.hasErrors()) 
       { 
        return new ModelAndView("error/error", "command",new String()); 
       } 
       else{ 
        return new ModelAndView("bankDetails/bankDetails", "command",bean);  
       } 
    } 

BankDetails bean包含EntityBankDetails的ArrayList中。我已經申請驗證,EntityBankDetail的領域如

public class EntityBankDetail { 
    @NotNull 
    @Size(max = 3) 
    private String nameOfBank; 
    private Double EMIforProposedLoan; 
    private String nameOfBranch; 
    private String accountType; 
    private String accountNumber; 
    private String applicantType; 
//Getters and Setters 
    } 

和我BankDetail字段中輸入3點以上的字符 這樣,我得到控制檯控制器的輸出作爲

false 
3 
fsdafsdfsdaf 

爲什麼我的驗證不起作用?我做錯了什麼?請諮詢..

編輯包括BankDetailBean

/* 
* This class represent the entire Bank Details Page. It can contain 0-4 EntityBankDetais 
* */ 
public class BankDetails { 

    private ArrayList<EntityBankDetail> bankDetails; 

    private String[] entities; 
    @Size(max = 1) 
    private int noOfBankDetails; 

    public ArrayList<EntityBankDetail> getBankDetails() { 
     return bankDetails; 
    } 
    public void setBankDetails(ArrayList<EntityBankDetail> bankDetails) { 
     this.bankDetails = bankDetails; 
    } 
    public String[] getEntities() { 
     return entities; 
    } 
    public void setEntities(String[] entities) { 
     this.entities = entities; 
    } 
    public int getNoOfBankDetails() { 
     return noOfBankDetails; 
    } 
    public void setNoOfBankDetails(int noOfBankDetails) { 
     this.noOfBankDetails = noOfBankDetails; 
    } 
} 

我對這個bean該類EntityBankDetail解決不了輸入出現錯誤。兩者在同一個包裹中爲什麼如此?

+0

發佈你的'BankDetails' bean。 –

+1

將'@ Valid'添加到您的'bankDetails'屬性。否則驗證器將不檢查它。 –

回答

1

在使用spring-mvc時,應該在應用程序上下文配置中指定<mvc:annotation-driven />以便能夠在控制器中使用JSR-303驗證。或者你可以配置LocalValidatorFactoryBean的實例並將其傳遞給<mvc:annotation-driven validator="yourValidator" />