BindingResult不会从.properties文件中获取消息,也不会在jsp

时间:2017-07-12 04:19:10

标签: java spring jsp bean-validation

我使用 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(“错误:”+ 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>

1 个答案:

答案 0 :(得分:0)

考虑为该表单编写验证器,然后您可以轻松地提供您需要的任何文本,例如

s = "eFdss"
s = list(s)
all(i.islower() for i in s )   # FALSE
any(i.islower() for i in s )   # TRUE