【发布时间】:2017-12-16 07:57:49
【问题描述】:
我使用 BindingResult 来验证 jsp 表单,我使用 message.properties 文件来设置所有验证消息。当我打印结果时,它显示 console 中有一些错误,但没有显示 message.properties 文件中的正确消息,甚至没有显示 jsp 文件中的错误。
我是否需要在控制器类中包含任何注释才能从 message.properties 获取数据?
配置
//other annotations
public class WebConfig extends WebMvcConfigurerAdapter{
//other stuffs
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
message.properties
Size.companyForm.companyName= size is invalid.
模型类
public class Company {
//other stuffs
@Size(min=2,max=30)
private String companyName;
}
公司控制人
@RequestMapping("/add")
public ModelAndView addCompany(Model modelAttr) {
ModelAndView model = new ModelAndView("addCompanyTiles");
model.addObject("companyForm", new Company());
return model;
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView saveCompany(@ModelAttribute("companyForm") @Valid Company company, BindingResult result) {
if(result.hasErrors()){
System.out.println("Errors : "+result.toString());
return new ModelAndView("redirect:/company/add");
}
companyService.saveOrUpdate(company);
return new ModelAndView("redirect:/company/list");
}
当我使用 System.out.println("Errors :"+result.toString()); 时,控制台中显示这里错误
Field error in object 'companyForm' on field 'companyName': rejected value []; codes [Size.companyForm.companyName,Size.companyName,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [companyForm.companyName,companyName]; arguments []; default message [companyName],30,2]; default message [size must be between 2 and 30]
jsp文件
<form:form action="${saveURL} " modelAttribute="companyForm">
// For easiness, I deleted other fields and styles
<form:input path="companyName"/>
<form:errors path="companyName" class="help-inline" />
</form:form>
【问题讨论】:
标签: java spring jsp bean-validation