Enterprise Java

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.

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.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button