Create a validator object from a class
You may want directly the an object after vaidator check if the form has errors or not ?
Now you can, and this is very simple.
Getting the object
This is really simple just do that:
Optional<UserDto> userDto = validator.get(UserDto.class);
Caution:
- If no check, check will be executed before parsing object.
- A constructor of the class need to be without parameters.
- If a field form doesn't exist in the class will be ignored.
- If a field is marked as optional value of the field in the class will be null if no field found in form.
You need to do nothing if...
If you didn't have nested object in your class.
This class doesn't contain a nested object:
public class UserDto {
private String name;
private String email;
private int age;
}
The ObjectParser support this list of objects:
- Integer, int
- Double, double
- Float, float
- Byte, byte
- Character, char
- Long, long
- String
Any other object to be supplanted to your object must have the annotation `CustomBinding` with the name of the function that returns the object field.
Inject data from form in nested object ?
I have this nested object
:
private class Location {
float x;
float z;
Location(float x, float z) {
this.x = x;
this.z = z;
}
}
And this class:
public class UserDto {
private String name;
private String email;
private int age;
private Location loc;
}
I need to add the anotation CustomBinding
.
public class UserDto {
private String name;
private String email;
private int age;
@CustomBinding("setLoc")
private Location loc;
}
The setLoc
is a function that return a Location
and take a Form
.
private Location setLoc(Form f) {
Optional<Float> x = f.getFloat("loc.x");
Optional<Float> z = f.getFloat("loc.z");
if (x.isPresent() && z.isPresent())
return new Location(x.get() , z.get());
return null;
}
Now this is okay. Enjoy !