【发布时间】:2015-09-21 19:12:14
【问题描述】:
我正在尝试使用 webResource.type.delete 删除记录。但是,我无法使用此方法删除。我试过使用 POSTMAN,我可以通过这个实用程序删除记录。我在执行中没有收到任何错误,只是servlet没有进入资源删除记录。
源码如下:
DeletePolicy.java(主 servlet):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
Client client= Client.create();
WebResource webResource= client.resource("http://localhost:8080/clientLibrary/webapi/policy");
//create an object of RequestDispatcher
RequestDispatcher rd = request.getRequestDispatcher("GetPolicy");
// send the client data available with req of delete to req of getPolicy with include()
rd.include(request, response);
List<Policy> policies = (List<Policy>) request.getAttribute("policies");
printWriter.print("List of policies in Delete: ");
for(Policy policy : policies) {
printWriter.println("<li>"+"ID: "+policy.getId()+"<br>"+"Max Number of Books: "+policy.getMax_books()+"<br>"+"Year of Book: "+policy.getYear_book()+"<br>"+"Activated: "+policy.getActivate()+"<br></li><br>");
}
//Show to the user the possible options to delete using radio button
request.setAttribute("policies", policies);
RequestDispatcher rd2 = getServletConfig().getServletContext().getRequestDispatcher("/showRecordsToDelete.jsp");
rd2.include(request,response);
printWriter.println("I am comming back from showRecordsToDelete.jsp");
//Receive the id from showRecordsToDelete.jsp
String policyID = request.getParameter("id");
ClientResponse rs = webResource.type(MediaType.APPLICATION_JSON).delete(ClientResponse.class);
//Receive the answer and provide status to user
printWriter.print("Delete a policy");
}
PolicyResource.java:
@Path("/policy")
public class policyResource {
policyDB db = new policyDB();
policyService PolicyService = new policyService();
@DELETE
@Path("/{policyID}")
@Produces(MediaType.APPLICATION_JSON)
public String removeBook(@PathParam("policyID") int ID){
System.out.println("id :"+ID);
boolean removed= PolicyService.deletePolicy(ID);
String answer="Removed successfully";
if(removed = false){
answer="Not removed";
}
return answer;
}
}
PolicyDB.java
/** Delete a policy
* @param id
* @return true if everything is done otherwise returns false
*/
public boolean delete(int id) {
Connection c = null;
System.out.println("delete id :"+id);
c = accessDB();
if (c != null) {
try {
Statement stmt = null;
// Execute a query
stmt = c.createStatement();
String sql = "DELETE FROM POLICIES WHERE ID='"+ id +"';";
System.out.println(sql);
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch ( Exception e ) {
// Handle errors for Class.forName
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
return false;
}
}
System.out.println("Deleted "+id);
return true;
}
提前感谢您的帮助
【问题讨论】: