How to handle String inputs for Integer fields
Development Process
If the user enters String input such as "abcde" for the Free Passes integer field, we'd like to give a descriptive error message.

We basically need to override the default Spring MVC validation messages.
Follow these steps.
1. In your Eclipse project, expand the node: Java Resources
2. Right-click the src directory and create a new sub-directory: resources
3. Right-click the resources sub-directory and create a new file named: messages.properties
Your directory structure should look like this:

4. Add the following entry to the messages.properties file
5. Save file
---
This file contains key/value pairs for the error message type
For a basic example:
typeMismatch.customer.freePasses=Invalid number
The format of the error key is: code + "." + object name + "." + field
To find out the given error code, in your Spring controller, you can log the details of the binding result
System.out.println("Binding result: " + theBindingResult);
6. Edit your config file: WEB-INF/spring-mvc-demo-servlet.xml
Add the following:
7. Save the file. Restart the Tomcat server
8. Run your app and add bad data for the "Free Passes" field. You will see the error message from our properties file.

Comments
Post a Comment