【问题标题】:Required String parameter 'text' is not present必需的字符串参数“文本”不存在
【发布时间】:2017-11-27 12:04:26
【问题描述】:

我正在尝试将一个字符串从我的视图发送到我的控制器,但我不断收到“文本”不存在的错误。

这是我的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);
    }

【问题讨论】:

  • 在发送前尝试对数据进行字符串化
  • 从查询参数中提取了一个@RequestParam 值。你没有。 data 是正文,为 json。

标签: javascript java angularjs spring-mvc spring-boot


【解决方案1】:

您可以尝试在您当前的data 中将前端更改为:

data = {params:{"text" : $scope.my.message}};

Spring 需要知道请求有参数。

或者您可以尝试将控制器中的 in 后端 @RequestParam(value= "text") String text 更改为 @RequestBody String text

看看RequestBody and RequestParam的区别

【讨论】:

  • 谢谢。我把它改成了@requestbody
【解决方案2】:

不确定 Spring 是否有办法将 {"text" : "some text"} 解析为原始字符串 "some text"。但是,@RequestParam 用于 URL 中的参数 (http://foo.com/post-stuff?text=text+here)。

POSTed 数据在正文中发送,因此您需要使用 @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);
}

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 2021-04-01
    • 2018-05-03
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多