Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring map GET request parameters to POJO automatically

Tags:

I have method in my REST controller that contains a lot of parameters. For example:

@RequestMapping(value = "/getItem", method = RequestMethod.GET) public ServiceRequest<List<SomeModel>> getClaimStatuses(         @RequestParam(value = "param1", required = true) List<String> param1,         @RequestParam(value = "param2", required = false) String param2,         @RequestParam(value = "param3", required = false) List<String> param3,         @RequestParam(value = "param4", required = false) List<String> param4,         @RequestParam(value = "param5", required = false) List<String> param5) {     // ...... } 

and I would like to map all GET request parameters to a POJO object like:

public class RequestParamsModel {     public RequestParamsModel() {     }     public List<String> param1;    public String param2;    public List<String> param3;    public String param4;    public String param5; } 

I need something like we can do using @RequestBody in REST Controller.

Is it possible to do in Spring 3.x ?

Thanks!

like image 517
IgorOK Avatar asked Oct 28 '14 15:10

IgorOK


1 Answers

Possible and easy, make sure that your bean has proper accessors for the fields. You can add proper validation per property, just make sure that you have the proper jars in place. In terms of code it would be something like

import javax.validation.constraints.NotNull;  public class RequestParamsModel {      public RequestParamsModel() {}      private List<String> param1;     private String param2;     private List<String> param3;     private String param4;     private String param5;      @NotNull     public List<String> getParam1() {         return param1;     }     //  ... } 

The controller method would be:

import javax.validation.Valid;  @RequestMapping(value = "/getItem", method = RequestMethod.GET) public ServiceRequest<List<SomeModel>> getClaimStatuses(@Valid RequestParamsModel model) {     // ... } 

And the request, something like:

/getItem?param1=list1,list2&param2=ok 
like image 98
Master Slave Avatar answered Nov 13 '22 09:11

Master Slave