I try to use REST on my web-project. POST works, but DELETE and PUT don't work, I will see the error: HTTP Status 405 - Method Not Allowed. And GET doesn't work at all:
""id": is not defined in RFC 2068 and is not supported by the Servlet API. description: The server does not support the functionality needed to fulfill this request."
This is my code:
package rest;
import domain.model.Client;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.*;
import javax.xml.bind.annotation.XmlRootElement;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
@XmlRootElement
@Path("/clients")
@Stateless
public class ClientResources {
@PersistenceContext
EntityManager entityManager;
@GET
@Consumes(MediaType.APPLICATION_JSON)
public Response getAll() {
List<Client> matchHistories = new ArrayList<>();
for (Client m : entityManager
.createNamedQuery("client.all", Client.class)
.getResultList())
matchHistories.add(m);
return Response.ok(new GenericEntity<List<Client>>(matchHistories) {
}).build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response Add(Client client) {
entityManager.persist(client);
return Response.ok(client.getId()).build();
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response update(@PathParam("id") int id, Client p) {
Client result = entityManager.createNamedQuery("client.id", Client.class)
.setParameter("clientId", id)
.getSingleResult();
if (result == null) {
return Response.status(404).build();
}
result.setName(p.getName());
result.setSurname(p.getSurname());
entityManager.persist(result);
return Response.ok().build();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("id") int id) {
Client result = entityManager.createNamedQuery("client.id", Client.class)
.setParameter("clientId", id)
.getSingleResult();
if (result == null) {
return Response.status(404).build();
}
return Response.ok(result).build();
}
@DELETE
@Path("/{id}")
public Response delete(@PathParam("id") int id) {
Client result = entityManager.createNamedQuery("client.id", Client.class)
.setParameter("clientId", id)
.getSingleResult();
if (result == null)
return Response.status(404).build();
entityManager.remove(result);
return Response.ok().build();
}
}
In Postman I wrote this:
{
"id" : 1,
"name" : "Adam"
}
Check your postman. You should have it set up as the image below. If your body type isn't
application/json
or your method isn'tPOST
you'll get the Method not allowed error.To get the HTTP/CURL/... call generated by Postman follow this image.
Your PUT service is reached from the path
/clients/{id}
as Mike noticed in the comments. So you'll have to call it with the ID of a client for PUT to work.