This example shows how to handle HTTP method DELETE request by using @DELETE annotation.
Example
Creating Resource
@Path("/orders")
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN})
public class OrderResource {
@GET
public Collection<Order> getOrders() {
return OrderService.Instance.getAllOrders();
}
@DELETE
@Path("{id}")
public boolean deleteOrderById(@PathParam("id") int id) {
return OrderService.Instance.deleteOrderById(id);
}
@GET
@Path("{id}")
public Order getOrderById(@PathParam("id") int id) {
return OrderService.Instance.getOrderById(id);
}
}
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Note that above resource methods define the same URI path, /orders/{id}, for @GET and @DELETE. In fact the same URI should be used for @PUT too. Per Restful API conventions, a URI path should never reflect an action like delete or get or create. A Restful URI should be like a resource. For different actions, we need to use HTTP method designator annotations, just like we used @DELETE and @GET in above example.
Writing Client
To test above resource methods, let's write JAX-RS clients.
public class ClientAllOrders {
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
//get all orders
WebTarget allOrderTarget =
client.target("http://localhost:8080/orders");
Response response = allOrderTarget.request().get();
List<Order> orders = response.readEntity(new GenericType<List<Order>>() {
});
orders.forEach(System.out::println);
}
}OutputOrder{id=1, item='item 1', qty=52, orderDate=Tue Oct 21 12:42:29 CST 2025} Order{id=2, item='item 2', qty=27, orderDate=Mon Oct 20 12:42:29 CST 2025} Order{id=3, item='item 3', qty=84, orderDate=Sun Oct 19 12:42:29 CST 2025} Order{id=4, item='item 4', qty=31, orderDate=Sat Oct 18 12:42:29 CST 2025} Order{id=5, item='item 5', qty=19, orderDate=Fri Oct 17 12:42:29 CST 2025}
Following client sends delete requests:
public class ClientDeleteById {
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
//delete multiple orders
for (Integer orderIdToDelete : Arrays.asList(2, 4)) {
WebTarget OrderByIdTarget =
client.target("http://localhost:8080/orders/" + orderIdToDelete);
boolean response = OrderByIdTarget.request().delete(Boolean.class);
System.out.println(response);
}
}
}Outputtrue true
Run ClientAllOrders class again:
Output
Order{id=1, item='item 1', qty=52, orderDate=Tue Oct 21 12:42:29 CST 2025}
Order{id=3, item='item 3', qty=84, orderDate=Sun Oct 19 12:42:29 CST 2025}
Order{id=5, item='item 5', qty=19, orderDate=Fri Oct 17 12:42:29 CST 2025}
Example ProjectDependencies and Technologies Used: - jersey-server 2.25.1 (Jersey core server implementation)
- jersey-container-servlet 2.25.1 (Jersey core Servlet 3.x implementation)
- JDK 1.8
- Maven 3.3.9
|