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?

2
  • 2
    For that there is @ModelAttribute. You might want to read the web section of the reference guide. Commented Nov 25, 2013 at 19:03
  • I already tried that but it didn't work; all bean attributes were null. Commented Nov 26, 2013 at 14:39

1 Answer 1

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";
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Note that this is equivalent to annotating the parameter with @ModelAttribute.
@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 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.
It works now, thanks, apparently it requires a setter, it doesn't work with public attributes. I will accept your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.