내 REST 웹 서비스에서 create 메소드를 편집하려고하므로 객체에서 새로 생성 된 ID를 반환해야합니다. 에 의해 (IT가 기반으로새롭게 생성 된 id restful service post
@POST
@Consumes({"application/xml", "application/json"})
@Path("withID")
@Produces("text/plain")
public String create2(Users entity) {
getEntityManager().persist(entity);
getEntityManager().flush();
System.out.println("new id: " + entity.getId());
return String.valueOf(entity.getId());
}
:
이
는 서버 측 방법을 만들 편집 ... 나는 지난 2 일 동안 노력 했어하지만 난 정말 뭔가 잘못하고 있어야합니다 아래 그림과 같이 넷빈즈) 발생 횟수() 메소드 : 나는 새로운 사용자 개체를 추가하는 내 클라이언트의 요청을 할 경우@GET
@Path("count")
@Produces("text/plain")
public String countREST() {
return String.valueOf(super.count());
}
, 그것은 예상대로처럼 작동합니다. 새 사용자가 데이터베이스에 추가됩니다. GlassFish 서버 로그에 System.out.println 명령으로 표시된 새로 생성 된 ID가 표시됩니다. 그러나 Netbeans의 TestRestful Web Services를 통해 테스트를 수행 한 경우 올바른 창에 클라이언트 생성 XML 코드를 붙여넣고 TEST 버튼을 누르면 HTTP 상태 415 - 지원되지 않는 미디어 유형 오류가 발생합니다.
나는 약간의 조사를했고 this 질문을 찾았습니다. 그래서 내 생각 엔 String을 반환하는 대신 201 CREATE 상태의 Response 객체를 반환하고 헤더 등을 조정해야합니까? 나는 봄 예제를 체크 아웃 그러나 나는 봄을 사용하고 있지 않다, 나는 그러나 내가 시도했던하지만 일부 조각 누락 ... 어떻게 작성 2 방법 코드를 조정하는 단서가 없다 :
@POST
@Consumes({"application/xml", "application/json"})
@Path("withID")
@Produces("text/plain") //should this change to application/xml?
public Response create2(Users entity) {
getEntityManager().persist(entity);
getEntityManager().flush();
System.out.println("new id: " + entity.getId());
//Response response = Response.created(... + "withID/" + entity.getId()); //response need an URI, can I get this through the entity object?
return Response.status(200).entity(entity.getId().toString()).build();
}
나는 희망을 나는 바른 길에있다. 긴 게시물에 대한 미안, 누군가가 나를 도울 수 있기를 바랍니다. 미리 감사드립니다!
편집 : 지금 예를 작업 :
@POST
@Consumes({"application/xml"})
@Path("withID")
@Produces({"application/xml"})
public Response create2(Users entity) {
getEntityManager().persist(entity);
getEntityManager().flush();
return Response.status(201).entity(entity.getId().toString()).build();
}
헤더를 조정할 필요가 없습니다. Response.created()는 제공 한 URI를 http 응답에 "Location"헤더로 자동 저장합니다. 이미 솔루션이있는 것 같습니다. –
안녕하세요 파벨, 난'javax.ws.rs.core에서만 찾을 수 있습니다.응답'다음의 메소드'public static Response.ResponseBuilder created (URI location)'을 참조하십시오. 생성 된 리소스에 대해 새 ResponseBuilder를 만들고 제공된 값을 사용하여 위치 헤더를 설정합니다. – Perneel