1

Developing a REST web service using Spring MVC which accepts a JSON request body. And process the received message further. Iam using following : Eclipse, Tomcat, Spring 3.0.1, Jackson lib, Curl for testing the web service


    `curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"fname":"my_firstname" , "lname":"my_lastname"}' http://localhost:8080/SpringMVC/restful`

returning

"Saved person: null null"

My controller class



        import com.samples.spring.Person;

    @Controller
    public class RestController {

    @RequestMapping(value="{person}", method = RequestMethod.POST)
    @ResponseBody
        public String savePerson(Person person) {
             // save person in database
            return "Saved person: " + person.getFname() +" "+ person.getLname();
        }

My person class




       package com.samples.spring;

    public class Person {

        public String fname;
        public String lname;

        public String getFname() {
            return fname;
        }
        public void setFname(String fname) {
            this.fname = fname;
        }
        public String getLname() {
            return lname;
        }
        public void setLname(String lname) {
            this.lname = lname;
        }
    }

user2870419
  • 43
  • 1
  • 6
  • Solved. Did two things as follows: 1.)Added @RequestBody 2.)Changed the Curl's JSON parameters from -d '{"fname":"my_firstname" , "lname":"my_lastname"}' ---- -d "{"""fname""":"""my_firstname""" , """lname""":"""my_lastname"""}". Can anyone explain this ??? – user2870419 Oct 11 '13 at 11:22

2 Answers2

6

try to add @RequestBody

@RequestMapping(value="{person}", method = RequestMethod.POST)
@ResponseBody
    public String savePerson(@RequestBody Person person) {
         // save person in database
        return "Saved person: " + person.getFname() +" "+ person.getLname();
    }
David
  • 698
  • 1
  • 7
  • 12
0

try to add a constructor your Person class:

public Person(String fname, String lname) {
    this.fname = fname;
    this.lname = lname;
}
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136