繁体   English   中英

必需的字符串参数“ text”不存在

[英]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.

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