我嘗試在我的web項目上使用REST。 POST工作,但DELETE和PUT不起作用,我會看到錯誤:HTTP狀態405 - 方法不允許。並獲得並不在所有的工作:REST - HTTP狀態405 - 不允許的方法
「& QUOT ; ID & QUOT ;:未在RFC 2068中定義,而不是由Servlet API支持說明:服務器不支持實現這一所需的功能請求。」
這是我的代碼:
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();
}
}
在郵差我寫了這個:
{
"id" : 1,
"name" : "Adam"
}
enter image description here enter image description here
我發現我的服務器只允許POST,GET,OPTIONS。我不知道如何改變這個配置。 Glassfish 4.0 – LuckyProgrammer