2

我想传递 ResourceBundle 的 (globalmessage.properties) 属性名称“ atm.number ”而不是硬编码文本“Número de cajero”作为“ errors.required ”属性的参数。我将如何在验证器中做到这一点?

ReporteIncidenciaValidator(验证器):

public class ReporteIncidenciaValidator implements Validator {

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

    public void validate(Object target, Errors errors) {
        ReporteIncidencia reporteIncidencia = (ReporteIncidencia) target;
        if (StringUtils.isBlank(reporteIncidencia.getNumeroCajero())) {
            errors.rejectValue("numeroCajero", "errors.required",
                new Object[]{"Número de cajero"}, "");
        }

    }
}

globalmessage.properties:

errors.required={0} es requerido.
atm.number=Número de cajero

servlet-context.xml:

...

<beans:bean id="messageSource"
  class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <beans:property name="basename" value="classpath:globalmessages" />
</beans:bean>

...

4

1 回答 1

1

一种简单的方法是使用 ApplicationContext 类

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <value>locale\messages</value>
        </property>
    </bean>

</beans>

public class ReporteIncidenciaValidator implements Validator, ApplicationContextAware  {
    private ApplicationContext ctx;


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

    public void validate(Object target, Errors errors) {
        String message = context.getMessage("yourKey", 
                new Object[] { }, Locale.US);
        // your code

    }
}
于 2012-06-19T22:45:59.823 回答