Spring map GET request parameters to POJO automatically

后端 未结 2 1047
太阳男子
太阳男子 2020-12-09 16:10

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

@RequestMapping(value = \"/getItem\", method = RequestMethod.GET)
public          


        
相关标签:
2条回答
  • 2020-12-09 16:57

    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
    
    0 讨论(0)
  • 2020-12-09 17:05

    Are you trying to do

    @RequestMapping(value = "/getItem", method = RequestMethod.GET)
    public ServiceRequest<List<SomeModel>> getClaimStatuses(@ModelAttribute RequestParamsModel requestParamModel) {
    ...
    }
    
    0 讨论(0)
提交回复
热议问题