繁体   English   中英

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

[英]Issue when mapping GET request parameters with DTO object in Spring Boot 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;
  }
}

这是我的回应对象

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”:“您好mvg”}

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

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

我得到这个输出

{“ responseMsg”:“您好空”}

我的问题是如何将请求参数中的“名字”与DTO的“名字”映射?

提前致谢

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

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

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

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

看到这个

首先,您需要选择需要(或想要使用)参数或模型的方法。 当您使用类似http://localhost:8080/sample/get?firstName=mvg ,您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;
}

暂无
暂无

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

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