在我的 Spring
启动应用程序中,我发送带有以下(例如)参数的 POST
数据:
data: {
'title': 'title',
'tags': [ 'one', 'two' ],
'latitude': 20,
'longitude': 20,
'files': [ ], // this comes from a file input and shall be handled as multipart file
}
在我的@Controller
中我有:
@RequestMapping(
value = "/new/upload", method = RequestMethod.POST,
produces = BaseController.MIME_JSON, consumes = BaseController.MIME_JSON
)
public @ResponseBody HttpResponse performSpotUpload(final SpotDTO spot) {
// ...
}
其中 SpotDTO
是一个非 POJO
类,具有所有 getter
和 setter
。
public class SpotDTO implements DataTransferObject {
@JsonProperty("title")
private String title;
@JsonProperty("tags")
private String[] tags;
@JsonProperty("latitude")
private double latitude;
@JsonProperty("longitude")
private double longitude;
@JsonProperty("files")
private MultipartFile[] multipartFiles;
// all getters and setters
}
不幸的是,当我收到请求时,所有字段都是 null
。 Spring 无法将参数映射到我的 DTO
对象。
我想我缺少一些配置,但我不知道是哪一个。
其他类似的问题只需在 DTO
类上设置字段访问器即可解决。这对我不起作用。
我还注意到,如果我在方法中指定每个参数:
@RequestParam("title") final String title,
请求甚至没有到达该方法。我可以在 LoggingInterceptor
preHandle
方法中看到传入请求,但在 postHandle
中什么也看不到。返回一个 404
响应。
最佳答案
我想你只是错过了 @RequestBody
参数注释:
@RequestMapping(
value = "/new/upload", method = RequestMethod.POST,
produces = BaseController.MIME_JSON, consumes = BaseController.MIME_JSON
)
public @ResponseBody HttpResponse performSpotUpload(@RequestBody final SpotDTO spot) {
// ...
}
关于java - 将 post 参数映射到请求中的 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48936069/