2016-11-15 38 views
2
@PatchMapping("/update") 
HttpEntity<String> updateOnlyIfFieldIsPresent(@RequestBody Person person) { 
    if(person.name!=null) //here 
} 

如何區分未發送值和空值?如何檢測客戶端是否發送空字段或跳過的字段?@RequestBody如何區分未發送值和空值?

+0

我想你幾乎不知道,因爲它會被視爲由Spring MVC – DamCx

+0

的可能重複同樣的方式(HTTPS [如何在彈簧安置控制器部分更新空,而不是提供值區分]:// stackoverflow.com/questions/38424383/how-to-distinguish-between-null-and-not-provided-values-for-partial-updates-in-s) – laffuste

回答

2

上述解決方案需要對方法簽名進行一些更改以克服請求主體到POJO(即Person對象)的自動轉換。

方法1: -

而不是請求體轉換成POJO類(人),您可以接收對象爲地圖和檢查爲重點「名」的存在。

@PatchMapping("/update") 
public String updateOnlyIfFieldIsPresent1(@RequestBody Map<String, Object> requestBody) { 

    if (requestBody.get("name") != null) { 
     return "Success" + requestBody.get("name"); 
    } else { 
     return "Success" + "name attribute not present in request body";  
    } 


} 

方法2: -

接收請求體作爲字符串並檢查字符序列(即名稱)。

@PatchMapping("/update") 
public String updateOnlyIfFieldIsPresent(@RequestBody String requestString) throws JsonParseException, JsonMappingException, IOException { 

    if (requestString.contains("\"name\"")) { 
     ObjectMapper mapper = new ObjectMapper(); 
     Person person = mapper.readValue(requestString, Person.class); 
     return "Success -" + person.getName(); 
    } else { 
     return "Success - " + "name attribute not present in request body"; 
    } 

}