Spring 当使用有效 JSON body 发出请求时,RestController 映射方法具有 object 和空字段

Spring RestController Mapping method has object with null fields when making request with valid JSON body

我正在尝试在 @RestController 中测试我的 @PostMapping。 该控制器看起来像这样:

@RestController
public class MyTestController
{
    private static final Logger logger = LogManager.getLogger();

    @PostMapping(path = "/foo")
    public String add(@Valid Boo boo, HttpServletRequest request)
    {
        if (LoadManager.insert(request.getRemoteAddr()) < 3)
            try
            {
                BooManager.persist(boo);
                return "1";
            }
            catch (Exception e)
            {
                logger.error(ExceptionUtils.getStackTrace(e));
            }
        return "0";
    }
}

然而,当我发出 post 请求并在该添加方法中调试期间查看 boo object 时,boo 字段全部为空。

请求body:

{
    "officialName" : "test",
    "phone" : "test",
    "email" : "test",
    "churchArea" : "test",
    "deanery" : "test",
    "town" : "test",
    "pass" : "test152S56"
}

请求headerContent-Type设置为application/json

嘘class:

@Data
public class Boo
{
    @Size(max = 1000)
    @NotBlank
    private String officialName;

    @Size(max = 100)
    @NotBlank
    private String phone;

    @Size(max = 100)
    @NotBlank
    private String email;

    @Size(max = 100)
    @NotBlank
    private String churchArea;

    @Size(max = 100)
    @NotBlank
    private String deanery;

    @Size(max = 100)
    @NotBlank
    private String town;

    @Size(max = 1000)
    @NotBlank
    private String pass;
}

@Data 注释来自 lombok,它生成 public getter 和 setter class。

当您需要将请求主体绑定到方法参数时,您应该使用@RequestBody 注解。这就是你的 Boo 对象属性为空的原因。

@PostMapping(path = "/foo")
public String add(@RequestBody Boo boo, HttpServletRequest request)

文档: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestBody.html