Search code examples
springspring-mvcdtohttp-request-parameters

DTO has only null with GET request params, but not POST @RequestBody


I'm trying to get my query params in a DTO like in this question but my DTO has always null value.

Is there anything wrong in my code ? I made it as simple as possible.

Queries:

GET http://localhost:8080/api/test?a=azaz => null

POST http://localhost:8080/api/test with {"a":"azaz"} => "azaz"

Controller with a GET and a POST:

@RestController
@RequestMapping(path = {"/api"}, produces = APPLICATION_JSON_VALUE)
public class MyController {

    // GET: dto NOT populated from query params "?a=azaz"
    @RequestMapping(method = GET, path = "test")
    public @ResponseBody String test(TestDto testDto){
        return testDto.toString(); // null
    }

    // POST: dto WELL populated from body json {"a"="azaz"}
    @RequestMapping(method = POST, path = "test")
    public @ResponseBody String postTest(@RequestBody TestDto testDto){
        return testDto.toString(); // "azaz"
    }

}

DTO:

public class TestDto {
    public String a;

    @Override
    public String toString() {
        return a;
    }
}

Thanks !

Full Spring boot sample to illustrate it


Solution

  • The problem is that you are missing setter for the field.

     public void setA(String a) {
        this.a = a;
    }
    

    should fix it.