2014-10-10 7 views
1

내가스프링 MVC RESTful 서비스 응답

Response.status(Response.Status.NOT_FOUND) 

나는이는 응답 본문에서 올바르게 설정되어있는 것을 볼 수 있습니다를 설정 내가받을 이유는 어떤 생각 "1.1 200 OK HTTP를 /"?

curl -v http://my_host/api/v1/user/99999999 

HTTP/1.1 200 OK

액세스 제어 - 허용 - 원산지 : *

는 액세스 제어가-허용-방법은 : POST는 GET, 옵션,

삭제

....

{ "statusType": "NOT_FOUND", "entity": "ID가 인 제품을 검색 할 수 없습니다. : 99999999 ","entityType ":"java.lang.String의 ","상태 ": 404,"메타 데이터 ": {}}

@RequestMapping(value="/product/{id}", method=RequestMethod.GET) 
@ResponseBody 
public Response getProduct(@PathVariable String id) { 

    Product product = null; //productService.getProduct(id); 
    if (product == null) { 
     // I KNOW I GET HERE !!! 
     return Response.status(Response.Status.NOT_FOUND).entity("Unable to retrieve product with id:"+id). build(); 
    } 

    // AS EXPECTED I DO NOT GET HERE 
    Map<String, Object> json = productRenderer.renderProduct(....); 
    return Response.ok(json, MediaType.APPLICATION_JSON).type("application/json").build(); 
} 

BTW 봄 버전을 사용하고 3.2.10

+0

확실하지 :

@ResponseStatus(value = HttpStatus.NOT_FOUND) public class ProductNotFoundException extends Exception { ... } 

는 따라서 내 원래의 방법은 지금과 같다 :

<bean id="..." class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> 

내가 org.springframework.web.bind.annotation.ResponseStatus 주석 사용자 정의 예외를 던져 문제를 해결하기 위해 컨트롤러 레벨에서. 작동 여부를 확인하기 위해 다른 상태 코드를 시도해 보셨습니까? – NMK

+0

@NMK 방금 Response.Status.FORBIDDEN 및 Response.Status.CONFLICT로 시도했지만 아무 소용이 없습니다. 한번 더 시체는 정확하지만 HTTP/1.1은 200입니다. – Ithar

답변

1

돌아보십시오 봄의 ResponseEntity 대신. 그것은 나를 위해 작동하고 올바른 응답 상태로 설정 : 예를 들어

을 : 당신이 당신의 질문에 Response와 마찬가지로 또한 빌더 패턴을 사용할 수 있습니다

return new ResponseEntity<>(body, HttpStatus.OK); 

:

return new ResponseEntity<>(HttpStatus.NOT_FOUND); 

또는 몸

(다음 예는 ResponseEntity의 JavaDoc에서 가져온 것입니다.

return ResponseEntity 
     .created(location) 
     .header("MyResponseHeader", "MyValue") 
     .body("Hello World"); 

기타 d etails은 문서에서 찾을 수 있습니다

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

+0

방금 ​​ResponseEntity <> (HttpStatus.NOT_FOUND)로 시도했지만 HTTP/1.1은 200입니다. – Ithar

+0

방금 ​​간단한 Spring Boot app 제대로 작동했습니다. 프로젝트에 대한 정보를 더 제공하면 문제가 어디에서 발생할 수 있는지 판단 할 수 있습니다.또한 스프링 4로 업데이트하여 그 차이가 발생하는지 확인해 볼 수 있습니까? –

+0

도움을 주셔서 감사합니다. 스프링 4 업데이트는 옵션이 아닙니다 :(. 내 프로젝트는 스프링 3.2.10, Java 1.7, javax.ws.rs.core.Response jersey-core-1.17.1.jar SaopUI를 사용합니다 RAW 액세스 제어 허용 방법 : POST, GET, OPTIONS, DELETE 콘텐츠 유형 : application/json; charset = UTF-8 전송 인코딩 : 청크 날짜 : 2014 년 10 월 10 일 11:22:12 GMT { "statusType": "NOT_FOUND", "entity": "제품을 검색 할 수 없습니다.", "entityType": "java.lang.String", "status": 404, "metadata": {}} – Ithar

0

이 문제의 원인은 응답 개체 인해 MappingJacksonHttpMessageConverter 빈의 설정에 JSON으로 렌더링 된되었다는 사실 때문이었다. 따라서 HTTP 응답은 항상 200이되고 응답 본문에는 javax.ws.rs.core.Response의 JSON 표현이 포함됩니다. 당신이 404을 설정할 수있는 경우

@RequestMapping(value="/product/{id}", method=RequestMethod.GET) 
@ResponseBody 
public Response getProduct(@PathVariable String id) throws ProductNotFoundException { 
    ... 
} 
관련 문제