1

使用接受 JSON 请求正文的 Spring MVC 开发 REST Web 服务。并进一步处理收到的消息。我正在使用以下内容:Eclipse、Tomcat、Spring 3.0.1、Jackson lib、Curl 来测试 Web 服务


    `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`

返回

"Saved person: null null"

我的控制器类



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

我的人班




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

4

2 回答 2

6

尝试添加@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();
    }
于 2013-10-11T10:23:16.987 回答
0

尝试为您的 Person 类添加一个构造函数:

public Person(String fname, String lname) {
    this.fname = fname;
    this.lname = lname;
}
于 2013-10-11T10:21:26.940 回答