在请求中将发布参数映射到DTO

时间:2018-02-22 19:52:14

标签: java spring spring-mvc spring-boot java-8

在我的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类,所有getterssetters

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响应。

2 个答案:

答案 0 :(得分:5)

我认为你错过了参数的@RequestBody注释:

@RequestMapping(
        value = "/new/upload", method = RequestMethod.POST,
        produces = BaseController.MIME_JSON, consumes = BaseController.MIME_JSON
)
public @ResponseBody HttpResponse performSpotUpload(@RequestBody final SpotDTO spot) {
    // ...
}

答案 1 :(得分:1)

您应该在@RequestBody之前添加SpotDTO spot注释。即 @RequestBody SpotDTO spot

 public @ResponseBody HttpResponse performSpotUpload(@RequestBody SpotDTO spot) {
    // ...
  }
相关问题