在RESTful Web服务中添加删除方法

Lev*_*Lev 2 java mysql rest

我正在制作我的第一个RESTful Web服务(使用MySQL)。但是我不知道如何通过ID从表中删除记录。

到目前为止,这是我所做的:

  1. 通过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
    
    Run Code Online (Sandbox Code Playgroud)
  2. 通过id搜索一个人并以JSON格式返回结果(id,全名和年龄):

    @GET
    @Path("/getPersonByIdJSON/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Person getPersonById(@PathParam("id")int id){
        return personDao.getPersonById(id);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 输出所有人并以JSON格式返回结果(id,全名和年龄):

    // the method returns list of all persons
    @GET
    @Path("/getAllPersonsInXML")
    @Produces(MediaType.APPLICATION_XML)
    public List<Person> getAllPersonsInXML(){
        return personDao.getAllPersons();
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 在数据库中插入一个人:

    //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\"}";
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. 在数据库中编辑一个人:

    //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\"}";
        }    
    }
    
    Run Code Online (Sandbox Code Playgroud)

Jas*_*McD 5

如果要删除资源:

@DELETE
@Path("/{id}")
public void deleteById(@PathParam("id")int id){
   personDao.deleteById(id);
}
Run Code Online (Sandbox Code Playgroud)

只要您构造了deleteById方法,那就谢谢!

意见建议:

  • 您的插入内容是GET。由于您正在创建某些内容,因此应该真正是POST。
  • 您的更新是GET。应该真的是一个PUT。玩得开心并坚持下去!!