Home » Java » Enterprise Java » Spring MVC Binding w/o Setters

About Calen Legaspi

Calen Legaspi
Calen is CEO and founder of Orange & Bronze Software Labs (http://orangeandbronze.com), an outsourcing, consulting & training firm based in Manila, specializing in Agile Software Development, Spring Framework and Grails. He is an advocate and trainer of Test-Driven Development, Object-Oriented Design, and Domain-Driven Design.

Spring MVC Binding w/o Setters

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.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
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

Leave a Reply

avatar

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

  Subscribe  
Notify of