[英]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)。
首先,您需要選擇需要(或想要使用)參數或模型的方法。 當您使用類似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.