Youlfey
Youlfey

Reputation: 605

How to bind @RequestParam to similar objectsin Spring?

I have simple POJO object with class:

public class Place
{
    @NotNull
    private String country;
    @NotNull
    private String city;
}

How to bind such objects to RequestParam as the here:

 public ResponseEntity find(@RequestParam String date, Place departure, Place arrival) 

Use api :

/find?date=2019-02-10T16:00:00&country=Russia&city=Samara&country=Russia&city=Moscow

get Response with use

System.out.println(departure);
System.out.println(arrival);

Place{country='Russia,Russia', city='Samara,Moscow'}

Place{country='Russia,Russia', city='Samara,Moscow'}

Can I get response as next:

Place{country='Russia', city='Samara'}

Place{country='Russia', city='Moscow'}

Upvotes: 0

Views: 39

Answers (1)

CharlieNoodles
CharlieNoodles

Reputation: 356

The problem is that Spring cannot differentiate your parameters with the same names, and stack them. For such a small business object as a parameter, I would explicitly create a different name in a specific parameter object.

public void find(@RequestParam String date, Travel travel)

With an Object like this:

public class TravelDto {

  @NotNull
  private String fromCountry;
  @NotNull
  private String fromCity;
  @NotNull
  private String toCountry;
  @NotNull
  private String toCity;
....
}

For your situation it would makes things clear from the HTTP cal point of view:

/find?date=2019-02-10T16:00:00&fromCountry=Russia&fromCity=Samara&toCountry=Russia&toCity=Moscow

Upvotes: 1

Related Questions