简体   繁体   English

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

[英]Map post parameters to DTO in request

In my Spring boot application, I'm sending the POST data with the following (eg) params: 在我的Spring启动应用程序中,我使用以下(例如)params发送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
    }

In my @Controller I have: 在我的@Controller我有:

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

where SpotDTO is a non- POJO class with all getters and setters . 其中SpotDTO是一个包含所有getterssetters的非POJO类。

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
}

Unfortunately all fields are null when I receive the request. 不幸的是,当我收到请求时,所有字段都为null Spring is unable to map the parameters to my DTO object. Spring无法将参数映射到我的DTO对象。

I guess I'm missing some configuration but I do not know which one. 我想我错过了一些配置,但我不知道哪一个。


Other similar questions are resolved by just setting fields accessors on the DTO class. 只需在DTO类上设置字段访问器即可解决其他类似问题。 This does not work for me. 这对我不起作用。

Also I have noticed that if I specify each parameter in the method: 另外我注意到如果我在方法中指定每个参数:

@RequestParam("title") final String title,

the method is not even reached by the request. 请求甚至没有达到该方法。 I can see the incoming request in a LoggingInterceptor preHandle method, but nothing in postHandle . 我可以在LoggingInterceptor preHandle方法中看到传入的请求,但postHandle没有任何postHandle A 404 response is sent back. 发回404响应。

I think you're just missing the @RequestBody annotation on your parameter: 我想你只是错过了参数的@RequestBody注释:

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

You should add @RequestBody annotation before SpotDTO spot . 你应该在SpotDTO spot之前添加@RequestBody注释。 ie @RequestBody SpotDTO spot @RequestBody SpotDTO spot

 public @ResponseBody HttpResponse performSpotUpload(@RequestBody SpotDTO spot) {
    // ...
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM