yankee
yankee

Reputation: 40860

Simplest way to use composed object as RequestParam in Spring

To following is something like... pseudo code... To illustrate what I am looking for:

// Setters and Getters ommitted to keep the example short here:
class Address
{
  private String street;
  private String city;
}

class AddressBookEntry
{
  private String name;
  private Address address;
}

class MyController
{
  public void render(@RenderParam AddressBookEntry entry)
  {
    ...
  }
}

As you can see there are two POJOs (Address and AddressBookEntry). Now I would like to pass an AddressBookEntry to my Controller as http request parameter. I imagine that the URL looks like this: /target?entry.name=Random-Guy&entry.address.street=Random-Street&entry.address.city=Random-City.

As far as I understand @RenderParam doesn't work this way. I would have to create a PropertyEditor that takes a single string and construct my target Object from it, which means that I can't have an individual URL-param for each (sub-)property.

@ModelAttribute comes closer, but I could not find any hint if and how nesting of objects might work with this annotation. Additionally this annotation works without the "entry." prefix in my URL above which means that I need to make sure that I don't have multiple ModelAttributes that share a property name, correct? That sounds stressful.

How can I solve this?

Upvotes: 0

Views: 1177

Answers (1)

axtavt
axtavt

Reputation: 242786

It's the situation when you should use @ModelAttribute. It supports nested objects as you want.

If you need multiple @ModelAttributes, you can compose them into special class (for example, it you case that class can contain a field named entry of type AddressBookEntry, so that parameter names will be the same).

Upvotes: 1

Related Questions