You can bind form parameters to a domain model object even if the domain model object does not have setters. Just add a @ControllerAdvice class with an @InitBinder method that configures your application to field binding via the initDirectFieldAccess() method
package boottests.controllers;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
@ControllerAdvice
class BindingControllerAdvice {
@InitBinder
void initBinder(WebDataBinder binder) {
binder.initDirectFieldAccess();
}
}
Hereβs how my domain model looks like:
package boottests;
public class Person {
private final String firstname;
private final String lastname;
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
@Override
public String toString() {
return firstname + " " + lastname;
}
}
And hereβs my Controller:
package boottests.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import boottests.Person;
@Controller @RequestMapping("/person")
class PersonController {
@GetMapping
String postForm(Person person) {
System.out.println("YYY " + person + " YYY");
return "/";
}
}
And of course, my form, on index.html:
<form action="person" > Lastname: <input type="text" name="lastname"/> <br/> Firstname: <input type="text" name="firstname"/> <br/> <input type="submit" value="Submit"/> </form>
If you run this on Spring Boot, youβll see that the form parameters were correctly bound to the fields of the domain model.
Published on Java Code Geeks with permission by Calen Legaspi, partner at our JCG program. See the original article here: Spring MVC Binding w/o Setters Opinions expressed by Java Code Geeks contributors are their own. |
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Thank you!
We will contact you soon.
Tags
Spring MVC
π Photo of Calen Legaspi
Calen LegaspiOctober 6th, 2019Last Updated: October 4th, 2019
Calen LegaspiOctober 6th, 2019Last Updated: October 4th, 2019
0 274 1 minute read

This site uses Akismet to reduce spam. Learn how your comment data is processed.