天天看点

【异常】Required request parameter ‘xxx‘ for method parameter type xxxx is not present一 、需求描述二 、代码实现三 、错误描述

一 、需求描述

前端需要传年份,后端根据年份(year字段)查询对应的结果

二 、代码实现

实现方式,主要有三种方法,

(1)使用Get请求[email protected](“”)的方式

@GetMapping("/getEventTrendDistribution/{year}")
public R getEventTrendDistribution(@PathVariable("year") Integer year) {
     if (ObjectUtil.isNull(year)) {
         return R.failed("年份不能为空");
     }
     return trendStatisticsService.getEventTrendDistribution(year);
 }
           

(2)使用Get请求[email protected]的方式

@GetMapping("/getEventTrendDistribution")
public R getEventTrendDistribution(@RequestParam("year") Integer year) {
     if (ObjectUtil.isNull(year)) {
         return R.failed("年份不能为空");
     }
     return trendStatisticsService.getEventTrendDistribution(year);
 }
           

(3)使用Post请求[email protected]的方式

@PostMapping("/getEventTrendDistribution")
public R getEventTrendDistribution(@RequestBody JSONObject jsonData) {
     Integer year = jsonData.getInt("year", null);
     return trendStatisticsService.getEventTrendDistribution(year);
}
           

但是,因为需要兼容没有传年份的场景,此时需要返回近12个月的数据。

因此选择了用(3)的方式来交互。

三 、错误描述

而,如题的异常报Required request parameter ‘xxx’ for method parameter type xxxx is not present,主要是因为使用了(2)的方式,但是(2)用的是

@PostMapping

,所以出错了。

根本原因是因为@RequestParam不支持post请求

注解 支持的类型 支持的请求类型 支持的Content-Type 请求示例
@PathVariable url GET 所有 /test/{id}
@RequestParam url GET 所有 /test?id=1
@RequestBody Body POST/PUT/DELETE/PATCH json {“id”:1}