一尘不染

使用Spring MVC的REST Web服务在发布JSON时返回null

spring-mvc

使用Spring MVC开发可接收JSON请求主体的REST
Web服务。并进一步处理收到的消息。Iam使用以下工具:Eclipse,Tomcat,Spring 3.0.1,Jackson
lib,用于测试Web服务的Curl

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

阅读 237

收藏
2020-06-01

共1个答案

一尘不染

尝试添加@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();
    }
2020-06-01