spring:message 标记未解决 JSR-303 错误

JSR-303 errors not being resolved by spring:message tag

当前期

我有一个用例,我需要同时使用 Spring Validator 和 JSR-303 验证来验证 modelAttribute。验证工作完美。我的自定义 Spring 验证器出现的错误正在被充分翻译。另一方面,JSR-303s 可以工作(出现错误并且是绑定结果的一部分),但是代码没有被翻译。事实上,我看到了代码本身。

问题示例: 将一个字段留空(由下面的自定义验证器覆盖),另一个字段留空(由 JSR-303 注释覆盖)。

JSP 中的输出如下:

AppConfigController.java

public class AppConfigController {

@Autowired
private Validator jsr303Validator;

@Autowired
private AppConfigValidator appConfigValidator;

@InitBinder("appConfig")
protected void initBinder(WebDataBinder binder) {
    binder.addValidators(jsr303Validator, appConfigValidator);
    binder.setDisallowedFields("id");
}

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String processUpdate(@Valid @ModelAttribute AppConfig appConfig, 
                            BindingResult result,
                            SessionStatus status) {

        if(result.hasErrors()) {
            return UPDATE_VIEW;
        } else {

            ...

            status.setComplete();

            return SUCCESS_REDIRECT;
        }

    } else {
        return "common/error";
    }
}

}

AppConfigValidator.java

@Component
public class AppConfigValidator implements Validator {

@Override
public boolean supports(Class<?> clazz) {
    return AppConfig.class.isAssignableFrom(clazz);
}

@Override
public void validate(Object target, Errors errors) {

    AppConfig appConfig = (AppConfig) target;

    if (appConfig.isHomePageWarningEnabled()) { 
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "homePageWarningTitleFr", "error.homePageWarningTitleFr.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "homePageWarningTitleEn", "error.homePageWarningTitleEn.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "homePageWarningFr", "error.homePageWarningFr.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "homePageWarningEn", "error.homePageWarningEn.required");
    }
}

}

AppConfig.java

public class AppConfig extends BaseEntity implements Serializable {
    ...
    @NotEmpty(message = "error.applicationContactEmailAddress.required")
    @Email(message = "error.applicationContactEmailAddress.invalid")
    private String applicationContactEmailAddress = "";

    ...
}

我也遇到了自定义约束的问题,例如:

@Hostname(message = "error.smtpServerHostname.invalid")

WebConfig.java

@Bean
public ResourceBundleMessageSource messageSource() {

    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();

    String[] baseNames = {
            "resources.messages.layout.LayoutResources",
            "resources.messages.layout.MenuResources",
            "resources.messages.option.AppConfigResources",
            "resources.messages.global.GlobalResources",
            "resources.messages.contact.ContactResources",
            "resources.messages.currentsession.CurrentSessionResources",
            "resources.messages.welcome.WelcomeResources",
            "resources.messages.user.UserResources",
            "resources.messages.role.RoleResources",
            "resources.messages.profile.ProfileResources"
    };

    messageSource.setUseCodeAsDefaultMessage(true);
    messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
    messageSource.setBasenames(baseNames);

    return messageSource;
}

@Bean
public LocalValidatorFactoryBean jsr303Validator() {

    LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
    localValidatorFactoryBean.setValidationMessageSource(this.messageSource());

    return localValidatorFactoryBean;
}

自定义 JSP 标签(所以在 JSP 中显示错误总是 one-liner)

<spring:hasBindErrors name="${modelAttribute}">
<section id="errors-placeholder" class="alert alert-danger">
    <h3><spring:message code="header.errors" /></h3>
    <p>
        <ul>
            <spring:bind path="${modelAttribute}.*">
                <c:forEach var="error" items="${status.errors.allErrors}">
                    <li><spring:message message="${error}"></spring:message></li>
                </c:forEach>
        </spring:bind>
        </ul>
    </p>
</section>

在JSP

中的典型使用
<t:errors modelAttribute="appConfig"></t:errors>

** 在调试来自 AppConfigController.java 的 "result.hasErrors()" 行时 **

我的 JSR-303 错误代码(JSR-303 注释的 "message" 属性中的内容)似乎没有通过 Spring 得到 translated/processed。相反,它被放置在 "defaultMessage" 属性中。

org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'appConfig' on field 'applicationContactEmailAddress': rejected value []; codes [NotEmpty.appConfig.applicationContactEmailAddress,NotEmpty.applicationContactEmailAddress,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [appConfig.applicationContactEmailAddress,applicationContactEmailAddress]; arguments []; default message [applicationContactEmailAddress]]; default message [error.applicationContactEmailAddress.required]
Field error in object 'appConfig' on field 'homePageWarningTitleFr': rejected value []; codes [error.homePageWarningTitleFr.required.appConfig.homePageWarningTitleFr,error.homePageWarningTitleFr.required.homePageWarningTitleFr,error.homePageWarningTitleFr.required.java.lang.String,error.homePageWarningTitleFr.required]; arguments []; default message [null]

知道如何告诉 Spring 将我的代码添加到已按惯例添加的代码[]([NotEmpty.appConfig.applicationContactEmailAddress、NotEmpty.applicationContactEmailAddress、NotEmpty.java.lang.String、NotEmpty ])?

谢谢

我需要用花括号将自定义消息代码括起来,如下所示:

@NotEmpty(message = "{error.applicationContactEmailAddress.required}")

来源:

http://forum.spring.io/forum/spring-projects/web/75737-how-to-customize-jsr-303-error-messages?p=482719#post482719

希望这对某人有所帮助