Strecks simplifies data binding by allowing form properties to be bound to domain model objects using annotations. This allows data binding code to be removed from a Struts application. An example of form to domain model data binding in a vanilla Struts form is shown below:
/**
* Plain Struts form with data binding code
*/
public class HolidayBookingForm extends ActionForm
{
private String entryId;
private String title;
private String startDate;
private String days;
//getters and setters omitted
public void readFrom(HolidayBooking booking)
{
if (booking != null)
{
if (booking.getEntryId() != 0)
this.entryId = String.valueOf(booking.getEntryId());
if (booking.getEntryId() != 0)
this.days = String.valueOf(booking.getDays());
if (booking.getStartDate() != null)
this.startDate = new java.sql.Date(booking.getStartDate().getTime()).toString();
this.title = booking.getTitle();
}
}
public void writeTo(HolidayBooking booking)
{
if (booking == null)
throw new IllegalArgumentException("Booking cannot be null");
if (this.days != null)
booking.setDays(Integer.parseInt(this.days));
if (this.entryId != null)
booking.setEntryId(Long.parseLong(this.entryId));
// don't accept empty Strings
if (this.title != null && this.title.trim().length() > 0)
booking.setTitle(title);
// assume validation has been handled
if (this.startDate != null && this.startDate.trim().length() > 0)
booking.setStartDate(java.sql.Date.valueOf(startDate));
}
}
The Strecks version of the same code achieves the same result through annotations. The binding mechanism is extensible. Simple scalar form to domain object property bindings are shown in the example below. Binding of objects selected via drop down menus is also supported out of the box.
/**
* Strecks form with data binding annotations
*/
public class HolidayBookingForm extends ValidBindingForm
{
private String title;
private String startDate;
private String days;
//setters omitted
private HolidayBooking booking;
@BindSimple(expression = "booking.title")
public String getTitle()
{
return title;
}
@BindSimple(expression = "booking.startDate", converter = SQLDateConverter.class)
public String getStartDate()
{
return startDate;
}
@BindSimple(expression = "booking.days")
public String getDays()
{
return days;
}
public HolidayBooking getBooking()
{
return booking;
}
public void setBooking(HolidayBooking booking)
{
this.booking = booking;
}
}