在Spring Boot Rest中使用DTO对象映射GET请求参数时出现问题

时间:2016-06-07 09:35:46

标签: java spring spring-restcontroller spring-rest

我已经使用Spring REST应用程序创建了一个Spring Boot。

这是我的控制器代码。

@RestController
public class SampleController {

  @RequestMapping(value = "/sample/get", method = RequestMethod.GET, produces = "application/json")
  @ResponseBody
  public Response getResponse(SampleDTO dto) {
    Response response = new Response();

    response.setResponseMsg("Hello "+dto.getFirstName());

    return response;
  }
}

这是我的SampleDTO

public class SampleDTO {

  @JsonProperty("firstname")
  private String firstName;

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
}

这是我的Response对象

public class Response {

  private String responseMsg;

  public String getResponseMsg() {
    return responseMsg;
  }

  public void setResponseMsg(String responseMsg) {
    this.responseMsg = responseMsg;
  }
}

当我尝试以这种方式访问​​服务时

http://localhost:8080/sample/get?firstName=mvg

我得到了这个预期的输出

{“responseMsg”:“Hello mvg”}

当我尝试以这种方式访问​​服务时

http://localhost:8080/sample/get?firstname=mvg

我收到了这个输出

{“responseMsg”:“Hello null”}

我的问题是如何将请求参数中的'firstname'映射到DTO的'firstName'?

提前致谢

3 个答案:

答案 0 :(得分:0)

当您设置@JsonProperty(“firstname”)时,请确保导入此语句“import com.fasterxml.jackson.annotation.JsonProperty;”。如果您要发送更多属性并且您的bean类没有,那么您可以在bean名称的顶部设置@JsonIgnoreProperties(ignoreUnknown = true)。

您还缺少@RequestBody注释。你应该在getResponse方法中将其作为(@RequestBody SampleDTO dto)。

答案 1 :(得分:0)

只需使用名称与您的请求参数匹配的字段创建Pojo Java Bean。

然后使用此类作为请求处理程序方法的参数(不带任何其他注释)

see this

答案 2 :(得分:-1)

首先,您需要选择您需要(或想要使用)param或model的方法。当您使用类似http://localhost:8080/sample/get?firstName=mvg的内容时,您将数据作为请求参数传递。所以你需要使用@RequestParam注释。

使用@RequestParam注释的示例(使用在docs中解释)

    @RequestMapping(method = RequestMethod.GET)
public Response foo(@RequestParam("firstName") String firstName) {
    Response response = new Response();
    response.setResponseMsg("Hello "+ firstName );
    return response;
}
相关问题