当使用有效的JSON主体发出请求时,Spring RestController Mapping方法具有带有null字段的



我正试图在@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请求并在该add方法的调试过程中查看boo对象时,boo字段都为null。

请求主体:

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

请求报头Content-Type被设置为application/json

Boo类:

@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;
}

@数据注释来自lombok,它为该类生成公共getter和setter。

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

@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

相关内容

  • 没有找到相关文章

最新更新