Using @initBinder in Spring 3 Controller

This post shows a simple example of using @initBinder annotation in Spring 3 controller.

Consider the following domain model and controller for processing a order form submission:

domain model

public class Pizza {

@NotNull

private int quantity;

@NotNull

private PizzaBase base;

}

and

public class PizzaBase {

@NotNull

private long id;

}

controller

@Controller

public class BindExampleController {

@RequestMapping(value=”/example/submit.action”, method=RequestMethod.POST)

public String submitForm(@Valid @ModelAttribute(“pizza”) Pizza pizza) {

// method implementation here

}

}

In this example, an order form will use a drop down menu and send the id of the pizza base chosen. The controller therefore has to convert the base id into the corrresponding PizzaBase object. To do this, we need to:

(1) Create a custom property editor to handle pizza base id to PizzaBase object conversion. This can be easily done by subclassing PropertyEditorSupport:

public class PizzaBasePropertyEditor extends PropertyEditorSupport {

@Override

public void setAsText(String text) {

PizzaBase base = new PizzaBase();

base.setId(Long.parseLong(text));

setValue(base);

}

}

(2) Register above property editor to the controller using @initBinder annotation:

@InitBinder

public void initBinderAll(WebDataBinder binder) {

binder.registerCustomEditor(PizzaBase.class,  new PizzaBasePropertyEditor());

}

That’s it. The controller now expects a request parameter “base” corresponding to the id of the pizza base chosen. The custom property editor creates a PizzaBase object with same id and associates the object with the model attribute Pizza in the controller’s  submitForm() method before it is called.

Note that @initBinder has an optional attribute where you can specify the particular attribute(s) to apply the method. By default, it applies to all model attributes.

About Raymond Lee
Professional Java/EE Developer, software development technology enthusiast.

Comments are closed.