简体   繁体   中英

Required String parameter 'text' is not present

I'm trying to send a string from my view to my controller, but I keep getting the error that "text" is not present.

this is my 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);
        });     
    }

My rest controller :

@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);
    }

Not sure whether there is a way that Spring can de-json {"text" : "some text"} into the raw string "some text" . However @RequestParam is used for parameters within URLs ( http://foo.com/post-stuff?text=text+here ).

POST ed data is sent in the body, so you'll need to use the @RequestBody annotation. And since the body is a more complex type, I'd use a class that makes it easy to extract the value:

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);
}

You can try to change in frontend in your current data to:

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

Spring need to know that request has parameters.

Or you can try to change the in backend in your controller @RequestParam(value= "text") String text to @RequestBody String text

Check out the difference between RequestBody and RequestParam

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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