8

In Jersey there is @BeanParam annotation with which I can have request parameters mapped to bean attributes.

In Spring I can find only @RequestBody which obviously works with request body and not request parameters.

Is there a way to have request parameters mapped to a bean using Spring?

rustyx
  • 80,671
  • 25
  • 200
  • 267

1 Answers1

19

Simply create a Pojo Java Bean with fields with names that match your request parameters.

Then use this class as an argument for your request handler method (without any additional annotations)

public class Example {
   private String x;
   private Integer y;

   //Constructor without parameter needed!
   public Example(){}

   //Getter + Setter
}

@Controller
@RequestMapping("someUrl")
public class SomeController {

    @RequestMapping
    public String someHandler (Example example) {
          System.out.println(example.getX());
          return "redirect:someOtherUrl";
    }
}
Ralph
  • 118,862
  • 56
  • 287
  • 383
  • 2
    Note that this is equivalent to annotating the parameter with `@ModelAttribute`. – Sotirios Delimanolis Nov 26 '13 at 04:10
  • 1
    @SotiriosDelimanolis Well not entirely. This will always construct a new instance of an object, whereas `@ModelAttribute` can reuse an existing object from the session. So it is not fully equivalent... – M. Deinum Nov 26 '13 at 14:43
  • @M.Deinum With normal `@EnableWebMvc` config, the application registers two `ServletModelAttributeMethodProcessor` instances. One that handles arguments with `@ModelAttribute` (higher priority) and one that doesn't (catch all case). They work exactly the same way. So if there is a model attribute with the same name as the method parameter (or whatever it is resolved to), then that object will be used. The added benefit of `@ModelAttribute` is to set the name to a completely different value. This is done so that you provide your custom `HandlerMethodArgumentResolver` before the catch-all one. – Sotirios Delimanolis Nov 26 '13 at 16:02
  • 1
    It works now, thanks, apparently it requires a setter, it doesn't work with public attributes. I will accept your answer. – rustyx Nov 28 '13 at 19:19