我正在制作我的第一个 RESTful Web 服务(使用 MySQL)。但我不知道如何通过 id 从表中删除记录。
这是我到目前为止所做的:
通过 id 搜索一个人并以 XML 格式返回结果(id、全名和年龄):
private PersonDao personDao = new PersonDao(); //method which return a single person in xml @GET @Path("/getPersonByIdXML/{id}") @Produces(MediaType.APPLICATION_XML) public Person getPersonByIdXML(@PathParam("id")int id){ return personDao.getPersonById(id); } // return JSON response
通过id搜索一个人并返回JSON格式的结果(id,全名和年龄):
@GET @Path("/getPersonByIdJSON/{id}") @Produces(MediaType.APPLICATION_JSON) public Person getPersonById(@PathParam("id")int id){ return personDao.getPersonById(id); }
输出所有人员并以JSON格式返回结果(id,全名,年龄):
// the method returns list of all persons @GET @Path("/getAllPersonsInXML") @Produces(MediaType.APPLICATION_XML) public List<Person> getAllPersonsInXML(){ return personDao.getAllPersons(); }
在数据库中插入一个人:
//insert @GET @Path("/insertPerson/{fullName}/{age}") @Produces(MediaType.APPLICATION_JSON) public String saveNewPerson(@PathParam("fullName") String fullName, @PathParam("age") int age) { Person person = new Person(); person.setFullName(fullName); person.setAge(age); if (!personDao.savePerson(person)) { return "{\"status\":\"ok\"} id="+person.getId(); } else { return "{\"status\":\"not ok\"}"; } }
编辑数据库中的人物:
//update @GET @Path("/insertPerson/{id}/{fullName}/{age}") @Produces(MediaType.APPLICATION_JSON) public String updatePerson(@PathParam("id") int id, @PathParam("fullName") String fullName, @PathParam("age") int age) { Person person = new Person(); person.setId(id); person.setFullName(fullName); person.setAge(age); if (!personDao.savePerson(person)) { return "{\"status\":\"ok\"}"; } else { return "{\"status\":\"not ok\"}"; } }
最佳答案
如果您想要删除资源:
@DELETE
@Path("/{id}")
public void deleteById(@PathParam("id")int id){
personDao.deleteById(id);
}
只要构造了 deleteById 方法就可以了,谢谢!
建议:
- 您的插入是 GET。确实应该是一个 POST,因为您正在创建一些东西。
- 您的更新是 GET。真的应该是一个PUT。 玩得开心并坚持下去!!
关于java - 在 RESTful Web 服务中添加删除方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29401914/