【问题标题】:Spring Thymeleaf Hibernate Validation custom message not available on pageSpring Thymeleaf Hibernate Validation 自定义消息在页面上不可用
【发布时间】:2015-07-10 12:57:53
【问题描述】:

在下面的示例中,我在 @DecimalMin 注释上有一条自定义消息。从输出中您可以看到默认消息已正确插入到控制器方法中。

问题是我想在 html 页面上使用此消息。问题是 thymeleaf 抓取了代码列表中的第一个代码。我希望它使用自定义代码 {grossPay.custom.message} 但它已经解决了。它也不能作为错误代码使用。

任何建议将不胜感激

//inside propery file
grossPay.custom.message=Dont do that

//inside model
@DecimalMin(value="0.00",message="{grossPay.custom.message}")

//inside controller
public String postResult(@Valid @ModelAttribute("myModel") CustomModel model, BindingResult result) {
for (FieldError error : result.getFieldErrors()) {
                System.out.println("Field Error in field: " + error.getField() + " with default message: "+ error.getDefaultMessage());
                System.out.println("codes: ");
                for (String s : error.getCodes()) {
                    System.out.println(s);
                }
}

//output
Field Error in field: grossPay with default message: Dont do that
codes: 
DecimalMin.customModel.grossPay
DecimalMin.grossPay
DecimalMin.java.math.BigDecimal
DecimalMin

【问题讨论】:

  • 你解决过这个问题吗?

标签: java spring validation thymeleaf hibernate-validator


【解决方案1】:

这是由于缺少配置引起的。您需要在配置中定义它:

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private MessageSource messageSource;

    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
        factory.setValidationMessageSource(messageSource);
        return factory;
    }
}

见:https://github.com/spring-projects/spring-boot/issues/3071

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2012-03-03
    • 2017-01-23
    • 2012-01-31
    • 1970-01-01
    相关资源
    最近更新 更多