【springboot】controller用单个String接收数据

示例代码

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @PostMapping("/details")
    public Response<Map<String, Object> getDetails(@RequestParam String testId) {
        log.info("请求报文:{}", testId);
        // 省略业务层处理逻辑...
        return null;
    }
}

遇到的错误

错误1

用postman的raw调用,报错“Required String parameter 'testId' is not present”

解决方法

改用form-data或x-www-form-urlencoded调用,如下

此时的Content-Type为application/x-www-form-urlencoded;如果是form-data,Content-Type那就是multipart/form-data; boundary=<calculated when request is sent>

这个时候成功接收到参数,成功调用。

问题2

但是,把x-www-form-urlencoded下的参数前的复选框对号取消,再次报错“Required String parameter 'testId' is not present”

解决方法

    @PostMapping("/details")
    public Response<Map<String, Object> getDetails(@RequestParam(value = "testId", required = false) String testId) {
        log.info("请求报文:{}", testId);
        // 省略业务层处理逻辑...
        return null;
    }

@RequestParam注解的required属性改成false。如果testId字段需要填,再单独校验,如果不需要填,直接返回空的内容。


版权声明:本文为xiaoxiao_su123原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。