Spring mvc abstract annotations integer

I have an object.

public class MyObject { .... @Column(name = "a_number") @NotNull @NumberFormat(style = Style.NUMBER) @Min(1) private Integer aNumber; ... //getters and setters } 

In my controller, I have a @Valid annotation for my object that is being exposed. I have a validation working on all my other fields in the class (all their rows) except this number. If I enter a number from my form, it works fine, and if I break @Min (1), it will also give me the correct validation error. My problem however is that if you enter a string instead of a number, it throws a NumberFormatException.

I have seen many Integer examples and validations, but no one counts if you enter a string in a published form. Do I need to check where else? Javascript I would like a solution that is consistent with the rest of the spring check so that I can use this in other classes. I would just like to let you know that it must be numeric. I also tried using the @Pattern annotation, but apparently this is just for strings.

Suggestions?

+7
source share
2 answers

You can add the following to your file that manages your error messages (this is the general data that it looks for in the event of a type mismatch:

 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) 
+9
source

For those who do not understand this idea, here is what to do in spring 4.2.0 . Create the file name messages.properties in the WEB-INF > classes folder. And put the above type mismatch messages in this file. In the spring or servlet.xml create the following bean.

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

And for your model attribute, such as private Integer aNumber; in question, along with other validation rules, this rule is also used to convert type mismatches. In this case, you will receive your message.

 <form:errors path="aNumber"></form:errors> 

Hope this helps others.

+3
source

All Articles