美文网首页
Spring boot 复杂参数传递 @RequestBody

Spring boot 复杂参数传递 @RequestBody

作者: 云抱住阳光太阳没放弃发亮 | 来源:发表于2018-08-15 17:57 被阅读517次

    在多条件查询的表格场景中,因为需要传递的参数较多,@RequestParam需要更多的代码量,所以我个人采用@RequestBody的方式传递

    Controller中:

        @ResponseBody
        @PostMapping("/users")
        public Page<User> findAll(@RequestBody QueryParams queryParams) {
            return userService.findAll(queryParams);;
        }
    

    实体类:

    public class QueryParams {
        private int pageSize = 0;
        private int pageNumber = 15;
        private String searchText = "";
        private String sortName = "date";
        private String sortOrder = "desc";
        private List<Condition> conditions = Collections.emptyList();
    
        // get set 方法省略...
    }
    
        // 多重条件选择对象
    public class Condition {
        private String field;
        private String comparison;
        private String input;
        
        // get set 方法省略...
    }
    

    但访问该请求时,有可能会出现这样的错误:

    com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
    Cannot construct instance of `com.xxx.domain.QueryParams` 
    (no Creators, like default construct, exist): 
    cannot deserialize from Object value (no delegate- or property-based Creator)
     at [Source: (PushbackInputStream); line: 1, column: 2]
    

    遇到这种情况,请把使用@RequestBody的实体类的全部构造参数删除,包括其嵌套的实体类(QueryParams 类中嵌套的 Condition)。

    删除之后,运行正常。

    相关文章

      网友评论

          本文标题:Spring boot 复杂参数传递 @RequestBody

          本文链接:https://www.haomeiwen.com/subject/lzgwbftx.html