1

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);
    }
jackjoesmith
  • 951
  • 4
  • 20
  • 33

2 Answers2

1

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).

POSTed 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);
}
zapl
  • 63,179
  • 10
  • 123
  • 154
1

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

JUAN CALVOPINA M
  • 3,695
  • 2
  • 21
  • 37