0

I have a class setup like the following...

public class Person {
    protected String firstName;
    protected String lastName;
    protected Integer age;
    ...
}

A controller that looks like this...

@RequestMapping(value={"/person"}, method = RequestMethod.GET)
public void returnPerson(Person person, ModelMap model, HttpServletResponse response) {
    ....
}

And I am passing in a straight URL such as...

<a href="/person?firstName=John&lastName=Smith&age=18">Link</a>

Is it possible to pass all of these into the "Person" argument in my controller rather than making numerous @RequestParam arguments for each one? Especially if I am going to be passing in a good amount of params?

nobeh
  • 9,784
  • 10
  • 49
  • 66
user1015523
  • 334
  • 2
  • 6
  • 15

3 Answers3

1

Yes you can do that in the exact way you are describing as long as you are following the property naming convention for Person.

What problem do you get when you try it this way?

MahdeTo
  • 11,034
  • 2
  • 27
  • 28
  • Can I leave the controller methods as is or do I need to use `@RequestParam Person person`? When I pass in that URL I get a 415 media unsupported error when using `@ResponseBody Person person` – user1015523 Jul 01 '12 at 09:11
1

You can do exactly what you're asking for using model binding:

@ModelAttribute("person")
public Person getPerson() {
    return new Person();
}

@RequestMapping(value="/person", method=RequestMethod.GET)
public void handle(@ModelAttribute("person") Person person, BindingResult errors, ModelMap model, HttpServletRequest req) {
    ...
}

The model attribute will be initialised by the getPerson method and when the handle method fires, any parameters from the request will be automatically bound to corresponding properties in the new Person object. The BindingResult holds any errors as a result of the binding e.g. if you passed "XYZ" as the age field (an integer).

More information here http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html

Rob Beardow
  • 871
  • 5
  • 6
0

This question is also nicely answered here: Passing parameters from JSP to Controller in Spring MVC

read the answer carefully, hopefully you'll get your answer correctly.

Community
  • 1
  • 1
Ph03nIX
  • 173
  • 1
  • 10