Spring没有解决JSR-303错误:消息标记

时间:2015-07-20 14:47:50

标签: spring spring-mvc bean-validation

当前问题

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

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

JSP中的输出如下:

  • error.applicationContactEmailAddress.required(没有正确翻译的JSR-303错误)
  • 请输入法语主页警告标题。 (我的自定义验证程序错误消息已正确翻译)

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中显示错误始终是一行的)

<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>

**调试&#34; result.hasErrors()&#34;来自AppConfigController.java的行**

看起来我的JSR-303错误代码(&#34;消息&#34; JSR-303注释的属性中的内容)没有被Spring翻译/处理。相反,它被放置在&#34; defaultMessage&#34;属性。

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])?

谢谢

1 个答案:

答案 0 :(得分:0)

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

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

来源:

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

希望这有助于某人