2

I'm developing my first Spring 3 webapp. In Spring 2, we used to have formBackingObject load data from the database, then let Spring binding update some of the fields, and then onSubmit would persist those changes.

In Spring 3 it seems I have two options:

  1. Let the user edit 100% of the persistent object. This would mean that the object's ID would need to be a hidden field
  2. Create a form object which holds the editable data, and then map that onto the persistent object on submit

The first option is not truly an option, we cannot let the user edit all fields, and we'd rather not present data in hidden fields where anyone capable of pressing F12 can alter the values.

The second option seems like a decent design approach. However, it appears that it requires to essentially clone every editable, persistent class.

@Entity
public class Company {
    private String uuid; // not editable!
    .. 30 other properties, 2 are not editable
}

public class CompanyForm {
    .. 28 of above properties
}

and then some mapping mechanism with lots of

public void map(CompanyForm cf, Company c) {
    cf.setName(c.getName());
    .. 27 other set(get())
}

I'm praying this is not the "as designed" approach of Spring's MVC binding. However, all tutorial I've found so far are terribly trivial and implement option 1 from above. Does anyone have some suggestions for implementing option 2?

Thanks, Simon

Simon
  • 2,994
  • 3
  • 28
  • 37

3 Answers3

2

DataBinder API

Note that there are potential security implications in failing to set an array of allowed fields. In the case of HTTP form POST data for example, malicious clients can attempt to subvert an application by supplying values for fields or properties that do not exist on the form. In some cases this could lead to illegal data being set on command objects or their nested objects. For this reason, it is highly recommended to specify the allowedFields property on the DataBinder.

You can use it together with option 1

rdm
  • 330
  • 1
  • 4
  • 18
0

A pragmatic way would be to just ignore the non editable fields on the update statement.

gantners
  • 471
  • 4
  • 16
0

I have actually circumvented this in the past by using a @ModelAttribute annotation and detecting the PK on the request, if you do it this way Spring will use the object that is returned from @ModelAttribute and automatically copy the submitted object to it.

It's kind of a hack and not obvious to someone who comes in to maintain the code though.

Tim H
  • 338
  • 1
  • 2
  • 8