我正在关注这个问题---> Spring MVC: How to perform validation?
这是我的控制器代码
@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上遇到错误,无法解析Class EntityBankDetail的类型。两者都在同一个包中为什么会这样??
答案 0 :(得分:1)
在使用spring-mvc时,应在应用程序上下文配置中指定<mvc:annotation-driven />
,以便能够在控制器中使用JSR-303验证。或者,您可以配置LocalValidatorFactoryBean的实例并将其传递到<mvc:annotation-driven validator="yourValidator" />
。