自定义验证消息不起作用。我有一个域类:
...
@RooJpaActiveRecord
public class Letter {
@NotNull(message="{validation.number_empty}")
@Size(min=1,max=20, message="{validation.number_size}")
@Column(length=20, nullable=false)
private String number;
...
}
/WEB-INF/i18n/messages.properties:
#validation
validation.number_size=number must be more than 1 and less than 20 symbols
...
我想在表单提交期间验证该域类中的一些字段。验证有效,但我收到输出消息:
{validation.number_size}
不是预期的字符串:数字必须大于 1 且少于 20 个符号 在我的项目的其他地方,我成功地使用了属性文件中的消息。
/WEB-INF/spring/webmvc-config.xml
<bean
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
id="messageSource"
p:basenames="WEB-INF/i18n/messages,WEB-INF/i18n/application"
p:fallbackToSystemLocale="false">
</bean>
另外,我也尝试过,但没有成功:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:WEB-INF/i18n/messages</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
最佳答案
您需要一些额外的配置来使用 messageSource 自定义错误消息。
尝试以下操作:
/WEB-INF/spring/webmvc-config.xml:
...
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource" />
</bean>
在您的 Controller 类中:
...
import org.springframework.validation.Validator;
...
@Autowired
private Validator validator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
参见this引用手册部分了解详细信息。
关于Spring自定义验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24124799/