0

I have some problems with how spring binds parameters.

In my scenario I want a controller method that accepts only one query argument 'q':

@Controller
@RequestMapping("/home")
public class HomeController {

   @RequestMapping
   public void test(@RequestParam(value = "q") final String q) {
        System.out.println("> " + q);
   }

}

Now if I send the valid request in terms of my specification:

GET /home?q=cat

I get expected output:

> cat

And if I send the request that is not valid in terms of my specification, but remains valid as http request:

GET /home?q=cat&q=black

I get ambiguous and unexpected result ( I have idea about why spring doing it... arrays binding, etc. :) But it remains a surprise. ):

> cat,black

I can't use those parameters, they are can be invalid. But I have no simple way to validate request.

masted
  • 1,211
  • 2
  • 8
  • 14

1 Answers1

1

Define the parameter as List<String> and assert that it only has one single item.

@RequestMapping
public void test(@RequestParam(value = "q") final List<String> q) {

    if (q.size() > 1) {
        throw new IllegalArgumentException("Multiple 'q' parameters are not allowed.");
    }

    System.out.println("> " + q);
}
zagyi
  • 17,223
  • 4
  • 51
  • 48
  • Yeah, it is a first workaround which I used up (String[] in my case :) ). I'm looking for more elegant and 'springy' way to do it. But thanks anyway. :) – masted Feb 28 '13 at 13:10
  • You can try then the techniques described in [here](http://stackoverflow.com/q/6203740/1276804). – zagyi Feb 28 '13 at 13:44
  • Okay, I cant found much more elegant solution :) Sad sad. – masted Mar 01 '13 at 09:35