Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 856
Marko Pacak Avatar asked Mar 06 '23 20:03

Marko Pacak


1 Answers

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) {
    // ...
}
like image 150
Brian Avatar answered Mar 15 '23 06:03

Brian