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

标签 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
    
  2. 通过id搜索一个人并返回JSON格式的结果(id,全名和年龄):

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

    // the method returns list of all persons
    @GET
    @Path("/getAllPersonsInXML")
    @Produces(MediaType.APPLICATION_XML)
    public List<Person> getAllPersonsInXML(){
        return personDao.getAllPersons();
    }
    
  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\"}";
        }
    }
    
  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\"}";
        }    
    }
    

最佳答案

如果您想要删除资源:

@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/

相关文章:

java - 等价于 Java 中的#define?

java - 如何在spring boot中注册ServletContextListener

java - CallableStatement 无法识别 OUT 参数

mysql:慢查询日志: sleep (60)?

mysql - 使用 Google Cloud SQL 连接 3 个表,其中多个事件与每个表中的同一唯一 ID 相关联

java - 将属性文件合并到现有 Runabble jar 不起作用

sql - 如何使用连接编写此查询?

json - 为什么 Elasticsearch Bulk-API 使用 "Content-Type: application/json" header ?

javascript - jQuery.when - 当 ALL Deferreds 不再是 'unresolved'(解决或拒绝)时的回调?

java - 如何使用 Executor 创建 Jersey 2 客户端