[英]Required String parameter 'text' is not present
我正在嘗試將字符串從視圖發送到控制器,但我不斷收到“文本”不存在的錯誤。
這是我的javascript
$scope.sendMsg = function(){
console.log($scope.my.message);
data = {"text" : $scope.my.message};
$http({
method:'POST',
data:data,
contentType: "application/json; charset=utf-8",
dataType:"json",
url:'/post-stuff'
}).then(function(response){
console.log(response);
});
}
我的休息控制器:
@RequestMapping(value= "/post-stuff", method=RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<PostTextResult> postStuff(@RequestParam(value= "text") String text){
System.out.println(text);
return new ResponseEntity<PostTextResult>(stuff.postTextContent(text), HttpStatus.OK);
}
不確定Spring是否可以將json {"text" : "some text"}
為原始字符串"some text"
。 但是,@ @RequestParam
用於URL中的參數( http://foo.com/post-stuff?text=text+here
)。
POST
ed數據在正文中發送,因此您需要使用@RequestBody
批注。 而且由於body是更復雜的類型,因此我將使用一個類來簡化提取值的過程:
static class TextHolder {
private String text; // < name matters
// getter+setter omitted
}
public ResponseEntity<PostTextResult> postStuff(@RequestBody TextHolder text) {
System.out.println(text.getText());
return new ResponseEntity<PostTextResult>(stuff.postTextContent(text.getText()), HttpStatus.OK);
}
您可以嘗試將當前data
前端更改為:
data = {params:{"text" : $scope.my.message}};
Spring需要知道該請求具有參數。
或者您可以嘗試將控制器@RequestParam(value= "text") String text
的in后端更改為@RequestBody String text
看看RequestBody和RequestParam之間的區別
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.