1、获取对象实体类

controller

@ApiOperation("分页/筛选列表")
    @GetMapping("/history/page")
    public CommonResult<Page<History>> page(HistoryPageParam historyPageParam) {
        return CommonResult.data(historyService.page(historyPageParam));
    }

param

@Getter
public class HistoryPageParam {

    @ApiModelProperty(value = "当前页", required = true)
    private Integer current;

    @ApiModelProperty(value = "每页记录", required = true)
    private Integer size;

    @ApiModelProperty("创建时间开始")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date startTime;

    @ApiModelProperty("创建结束时间")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date endTime;
}

测试

http://xxxx:xx/history/page?current=1&size=10

java getMapping请求 传参_java

结果

空指针,获取不到传入的数据;

排查原因

  1. 未正确绑定参数: 确保HistoryPageParam类具有无参构造函数,并且具有相应的setter方法,以便Spring能够正确地绑定查询参数。
  2. 查询参数命名不匹配: 确保查询参数的名称与HistoryPageParam类的属性名称匹配。
  3. GET请求未正确处理: 确保GET请求中的参数及路径是正确的。

确定原因

未正确绑定参数: 确保HistoryPageParam类具有无参构造函数,并且具有相应的setter方法,以便Spring能够正确地绑定查询参数。但是我的没有,应该改为:

@Getter
@Setter
public class HistoryPageParam {

    @ApiModelProperty(value = "当前页", required = true)
    private Integer current;

    @ApiModelProperty(value = "每页记录", required = true)
    private Integer size;

    @ApiModelProperty("创建时间开始")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date startTime;

    @ApiModelProperty("创建结束时间")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date endTime;
}

2、获取List参数

controller

@ApiOperation("用户删除历史记录")
    @GetMapping("/history/del")
    public CommonResult<String> del(List<String> ids) {
        historyService.del(ids);
        return CommonResult.ok();
    }

测试

http://xxxx:xx/history/del?ids=1727969456940564481

java getMapping请求 传参_List_02

结果

服务器未知异常:java.lang.IllegalStateException: No primary or single unique constructor found for interface java.util.List, 请求地址:http://localhost:8822/history/del

排查原因

  1. GET请求中未正确传递参数: 确保您的GET请求的URL正确包含ids参数。例如,您的请求URL应该是类似于http://xxxx:xx/history/del?ids=1,2,3。请确保参数名和值都正确。
  2. Spring MVC未正确解析参数: 确保Spring MVC正确地解析和绑定查询参数。在您的情况下,List<String> ids应该是可以直接从查询参数中获取的。确保Spring MVC的配置正确,且没有覆盖默认的参数解析行为。
  3. List类型的参数处理问题: 在某些情况下,Spring MVC可能无法直接处理List类型的参数。您可以尝试将参数改为数组形式,即String[] ids,看看是否能解决问题。

原因

Spring MVC未正确解析参数: 确保Spring MVC正确地解析和绑定查询参数。在您的情况下,List<String> ids应该是可以直接从查询参数中获取的。确保Spring MVC的配置正确,且没有覆盖默认的参数解析行为。应该改为:

@ApiOperation("用户删除历史记录")
    @GetMapping("/history/del")
    public CommonResult<String> del(@RequestParam List<String> ids) {
        historyService.del(ids);
        return CommonResult.ok();
    }

在Spring MVC中,使用@RequestParam注解可以明确指定请求参数的名称,以确保参数正确地绑定到方法的参数。如果没有使用@RequestParam注解,并且参数类型是集合类(如List),Spring MVC 将尝试从请求中匹配参数名并将值绑定到该参数。

没有使用@RequestParam注解这可能导致Spring MVC在没有明确指定参数名的情况下无法正确解析请求参数。如果请求的URL中包含与方法参数名相同的查询参数,那么Spring MVC应该可以正确地解析参数,但是为了确保最大的清晰度和准确性,最好使用@RequestParam注解。

这样的方式更为明确,可读性更好,并且在存在多个参数的情况下,可以避免潜在的歧义。确保在使用@RequestParam注解时提供正确的参数名,以便Spring MVC能够正确地绑定请求参数。