REST Jersey Client

Tag: rest , jersey Author: caryan Date: 2014-03-30

I'm trying to create a RESTful web service and I can't get the delete working and I'm not sure where the problem is. I think the problem is somewhere in the client project but it could also be in the resource class in the server project.

I have a student dao class with this method, I don't think this is a problem because it is working for other projects.

    public void deleteStudent(String id){
    try {
        PreparedStatement pstmt;
        pstmt = con.prepareStatement("DELETE FROM APP.STUDENT WHERE ID = ?");
        pstmt.setString(1, id);
        pstmt.executeUpdate();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

I have a StudentResource class which I created as a RESTful resource from patterns with this code in it

    @DELETE
       public String delete(String id) {
       StudentServiceDAO studentsDAO = new StudentServiceDAO();
       StudentServiceEntry studentsEntry = studentsDAO.getStudent(id);
       studentsDAO.deleteStudent(id);
       return "<studentDeleted id = '"+id+"' />";
    }

Then I created a java project and created a RESTful java client called OneStudent with this method, I think this could be where the problem is

    public String delete(String id) throws ClientErrorException {
       webTarget.request().delete();
       WebTarget resource = webTarget;
       return   resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(String.class);
}

And I'm trying to test it from the main class like this

    OneStudent client = new OneStudent("A555222");
    Object response = client.delete("A555222");
    client.close();

Best Answer

Yes your client code is off a bit, but I also think it would be better to move the id to a path param like this:

@DELETE
@Path("/{id}")
public String delete(@PathParam("id") String id) {
    StudentServiceDAO studentsDAO = new StudentServiceDAO();
    studentsDAO.deleteStudent(id);
    return "<studentDeleted id = '"+id+"' />";
}

Then your client:

public String delete(String id) throws ClientErrorException {
    return webTarget.path(id)
                    .request(MediaType.APPLICATION_XML)
                    .delete(String.class);
}

Also you should not be manually constructing XML in your resource, but that's a different problem...