我在springboot的post body中发送请求它不工作

bz4sfanl  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(378)

我试图在restapi中使用springboot发布body,但我做不到。我受苦了好几个小时,直到现在我也找不到问题,为什么是什么原因,我不知道我犯了什么错误,请帮助我。
pojo类
个人.java

package com.thila.family.test;

import javax.annotation.Generated;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Person {

    @Id
    private int id;
    private String familyName;
    private String familyMembers;
    private long contactNo;
    public Person() {

        }

     public Person(int id,String familyName, String familyMembers,long contactNo) {
        super();
        this.familyName = familyName;
        this.familyMembers = familyMembers;
        this.contactNo = contactNo;
    }

    //getters setters
}

personservice.java文件

package com.thila.family.test;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

@Service
public class PersonService {

    private List<Person> persons=new ArrayList<>();
    public void addPerson(Person person) {
        persons.add(person);
    }

}

personcontroller.java

@RestController
public class PersonController {

    @Autowired
    private PersonService personService;

    @RequestMapping(method=RequestMethod.POST,value="/fam") 
    public void addPerson(@RequestBody Person person){
        personService.addPerson(person);        
    }
}

我对尸体的请求

{
   "id":"1",
    "familyName": "panchala",
    "familyMembers":"5",
    "contactNo":"234567"

}

我搞错了

{
    "timestamp": "2021-01-02T04:39:55.307+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "",
    "path": "/fam"
}

please help me I don't know why I got this error

4nkexdtk

4nkexdtk1#

在控制器类中

@RequestMapping(value = "/fam", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void addPerson(@RequestBody Person person){
{
....
}

只是一个建议,返回一个正确响应状态的响应也是很好的

@RequestMapping(value = "/fam", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity addPerson(@RequestBody Person person){
{
......
 return new ResponseEntity<>(HttpStatus.OK); 
}
vyswwuz2

vyswwuz22#

在personcontroller.java中,在 @RestController 注解:

@RequestMapping(value = "/person", produces = MediaType.APPLICATION_JSON_VALUE)

只有当出现这种情况时,控制器才会得到解析,并且路径会到达您试图调用的特定控制器方法。
现在您的url可能如下所示: localhost:8080/person/fam

相关问题