【问题标题】:spring mvc annotation validation integerspring mvc注解验证整数
【发布时间】:2011-12-21 07:52:07
【问题描述】:
我有一个对象。
public class MyObject
{
....
@Column(name = "a_number") @NotNull @NumberFormat(style = Style.NUMBER) @Min(1)
private Integer aNumber;
...
//getters and setters
}
在我的控制器中,我在发布的对象上有@Valid 注释。除了这个数字之外,我确实对班级中的所有其他字段(它们的所有字符串)进行了验证。如果我从表单中输入一个数字,它可以正常工作,如果我违反了@Min(1),它也会给我正确的验证错误。然而我的问题是,如果你输入一个字符串而不是一个数字,它会抛出一个 NumberFormatException。
我见过很多整数和验证的例子,但是没有人解释你是否在发布的表单中输入了一个字符串。我需要在其他地方进行验证吗? Javascript?我想要一个与 Spring 验证的其余部分一致的解决方案,以便我可以在其他类中使用它。我只想要一个错误,说明它必须是数字。我也尝试使用 @Pattern 注释,但显然那只是用于字符串。
建议?
【问题讨论】:
标签:
spring
spring-mvc
annotations
【解决方案1】:
仍然相关,所以我将添加消息源bean定义的编程方法:
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
【解决方案2】:
对于那些在这里没有得到这个想法的人来说,可以在spring 4.2.0 中做些什么。
在WEB-INF > classes 文件夹中创建一个文件名messages.properties。并将上述类型不匹配消息放入该文件中。
在 spring 配置或servlet.xml 文件中创建以下 bean。
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="messages"></beans:property>
</beans:bean>
对于问题中的private Integer aNumber; 等模型属性以及其他验证规则,此规则也适用于类型不匹配转换。您将在此收到您想要的消息。
<form:errors path="aNumber"></form:errors>
希望对其他人有所帮助。
【解决方案3】:
您可以将以下内容添加到控制错误消息的文件中(这些是它在类型不匹配的情况下查找的通用消息:
typeMismatch.commandObjectName.aNumber=You have entered an invalid number for ...
typeMismatch.aNumber=You have entered an invalid number for ...
typeMismatch.java.lang.Integer=You have input a non-numeric value into a field expecting a number...
typeMismatch=You have entered incorrect data on this page. Please fix (Catches all not found)