9
votes

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?

1
For that there is @ModelAttribute. You might want to read the web section of the reference guide. - M. Deinum
I already tried that but it didn't work; all bean attributes were null. - rustyx
Then you have a mismatch in the property names and your requestparameters. They should match. - M. Deinum
It works now, thanks, apparently it requires a setter, it doesn't work with public attributes. - rustyx
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

1 Answers

19
votes

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";
    }
}