payloc91
payloc91

Reputation: 3809

Map post parameters to DTO in request

In my Spring boot application, I'm sending the POST data with the following (e.g) params:

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:

@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.

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. Spring is unable to map the parameters to my DTO object.

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. 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. A 404 response is sent back.

Upvotes: 4

Views: 10015

Answers (2)

Hadi
Hadi

Reputation: 17289

You should add @RequestBody annotation before SpotDTO spot. i.e @RequestBody SpotDTO spot

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

Upvotes: 1

Brian
Brian

Reputation: 17309

I think you're just missing the @RequestBody annotation on your parameter:

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

Upvotes: 7

Related Questions