loading

Spring MVC - Get 请求获取参数可以不使用 @RequestParam,通过实体类封装并获取

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

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

  1. Service 接收 Map 对象,在 Controller 层把这些 URL 参数封装到 Map 中传递给 Service。
  2. 通过 @ModelAttribute 把 URL 参数封装到实体类中,传递给 Service。
  3. 不使用 @ModelAttribute 注解,而是直接在 Controller 层方法参数中写一个实体类,Spring 会自动把 Get 上面的 URL 参数封装到实体类中。

第一种 Map 由于在获取时数据类型不确定需要强转,并且 key 出错就会报错。

在这里的用法上,第二种是多余的写法,可以被第三种方式代替,也就是不写任何的注解,直接给实体类。

file:[controller/FlowchartController.java]
@GetMapping("/find/all/collect")
public R<List<CollectFlowchart>> findAllCollect(@ModelAttribute FlowchartCondition condition) {
lit:[public R<List<CollectFlowchart>> findAllCollect(FlowchartCondition condition) {]:lit
    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;

    }

}
posted @ 2023-10-05 02:45  Himmelbleu  阅读(13)  评论(0编辑  收藏  举报