Spring MVC - @ModelAttribute 注解代替 @RequestParam,通过实体类获取 Get 请求的参数

发布时间 2023-10-05 02:48:39作者: Himmelbleu

如果遇到 Get 请求参数过多的情况,使用 @RequestParam 不合适了,太多了也不好搞,而且如果遇到了增加或修改的情况,Service 层方法也要改变。

优化 Get 请求参数过多的方法有两种:

  1. Service 接收 Map 对象,在 Controller 层把这些 URL 参数封装到 Map 中传递给 Service。
  2. 通过 @ModelAttribute 自动把 URL 参数封装到实体类中,传递给 Service。

更合适的是第二种,第一种 Map 由于在获取时数据类型不确定需要强转,不安全,并且 key 出错就会报错,而且你也不知道获取的 key 是什么意思,好歹实体类可以有字段注释。

file:[controller/FlowchartController.java]
@GetMapping("/find/all/collect")
public R<List<CollectFlowchart>> findAllCollect(@ModelAttribute FlowchartCondition condition) {
    List<CollectFlowchart> list = collect.findAll(condition);
    if (list != null) return R.success(list);
    return R.failed("没有收藏流程图!", null);
}
file:[entity/vo/FlowchartCondition.java]
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FlowchartCondition {

    private String uid;
    private String fileName;
    private Integer isPublic;
    private Integer isLegal;
    private Integer isShare;
    private List<Collate> collates;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Collate {

        /**
         * 是否升序
         */
        private Boolean isAsc;

        /**
         * 字段名称
         */
        private String col;

    }

}