9

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
  • 73,455
  • 21
  • 176
  • 240
  • 2
    For that there is @ModelAttribute. You might want to read the web section of the reference guide. – M. Deinum Nov 25 '13 at 19:03
  • I already tried that but it didn't work; all bean attributes were null. – rustyx Nov 26 '13 at 14:39
  • Then you have a mismatch in the property names and your requestparameters. They should match. – M. Deinum Nov 26 '13 at 14:42
  • 1
    It works now, thanks, apparently it requires a setter, it doesn't work with public attributes. – rustyx Nov 28 '13 at 19:17
  • This is very common need and i see lot of duplicate and similar question posted in SO. Have you tried searching in google ? . If you put Jackson in classpath and if you create simple pojo should work. – Jayasagar Nov 29 '13 at 09:34

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
  • 115,440
  • 53
  • 279
  • 370
  • 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