Naga K
Naga K

Reputation: 753

Spring Post Controller always receives null

I have a controller as follows, but it always receives null.

@ResponseBody
      @RequestMapping(value="/saveAllData", method = RequestMethod.POST, consumes = "text/plain")
      @Override
      public String getAll(String jsonInput) {
        // TODO Auto-generated method stub
          System.out.println(jsonInput);
          return jsonInput;
    }

The java script call is as follows

$.ajax({
        url:"http://localhost:9090/saveAllData",
        type:"POST", 
        contentType: "text/plain",
        data: "Hi", //To avoid making query String instead of JSON
        success: function(resposeJsonObject){
            alert(resposeJsonObject);
}});

Spring controller always returns "null". This may be because it receives "null" in "jsonInput" parameter. Can anyone help solve this issue

Upvotes: 0

Views: 125

Answers (2)

ParagFlume
ParagFlume

Reputation: 979

Add @RequestBody

  @ResponseBody
  @RequestMapping(value="/saveAllData", method = RequestMethod.POST, consumes = "text/plain")
  @Override
  public String getAll(@RequestBody String jsonInput) {
    // TODO Auto-generated method stub
      System.out.println(jsonInput);
      return jsonInput;
}

Upvotes: 0

approxiblue
approxiblue

Reputation: 7122

You need to annotate the method parameter with @RequestBody, so Spring knows the parameter should be given the value of the HTTP request body.

Upvotes: 0

Related Questions