2017-12-08 2 views
1

스프링 4.3.8.RELEASE를 사용하고 있습니다. 특정 금지 된 오류에 대한 오류 메시지를 설정하려고합니다. 나는 내 컨트롤러에 이것을 가지고있다. "response"는 "javax.servlet.HttpServletResponse"유형입니다.어떻게 콘텐츠를 HttpServletResponse 버퍼에 출력합니까?

 response.setStatus(HttpServletResponse.SC_FORBIDDEN); 
     response.setContentLength(errorMsg.length()); 
     byte[] buffer = new byte[10240]; 
     final OutputStream output = response.getOutputStream(); 
     output.write(buffer, 0, errorMsg.length()); 
     output.flush(); 

그러나, 내용이 돌려지고하지 않는 것, 적어도 나는

final MvcResult result = mockMvc.perform(get(contextPath + "/myurl") 
        .contextPath(contextPath) 
        .principal(auth) 
        .param("param1", param1) 
        .param("param2", param2)) 
     .andExpect(status().isForbidden()) 
     .andReturn(); 
    // Verify the error message is correct 
    final String msgKey = "error.code"; 
    final String errorMsg = MessageFormat.format(resourceBundle.getString(msgKey), new Object[] {}); 
    Assert.assertEquals("Failed to return proper error message.", errorMsg, result.getResponse().getContentAsString()); 

어설 션이 말하는 실패 ... 내 단위 테스트에서 볼 수없는 응답 문자열 비어있었습니다. 응답을 HttpServletResponse 버퍼에 다시 쓰는 올바른 방법은 무엇입니까?

답변

2

를 사용할 수 있습니다.

뭔가

같은
response.getWriter().write(errorMsg) 

문제

+0

예. 줄을보십시오 - "output.write (buffer, 0, errorMsg.length());" – Dave

+2

아니요,'errorMsg.length()'바이트를'buffer'에서 0으로 시작하여 출력합니다. 그러나'errorMsg'를 복사하지 않았기 때문에'buffer'는 모두 0입니다. –

0

당신은 당신은 output 또는 buffererrorMsg 쓰기 결코 응답 기업에게

@RequestMapping("/handle") 
public ResponseEntity<String> handle() { 

    HttpHeaders responseHeaders = new HttpHeaders(); 
    responseHeaders.setLocation(location); 
    responseHeaders.set("MyResponseHeader", "MyValue"); 
    return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.FORBIDDEN); 
} 

Spring Response Entity

+0

어쩌면 좀 더 명확했다 shoudl. 어떻게 HttpSErvletResponse 주어진 출력 문자열을 생성합니까. 귀하의 대답은이 문제를 해결하지 못합니다. 고마워, - – Dave

0

좋은 일이 throw에 인수로 HttpServletResponse을 통과하거나 사용을 제공하는 경우 (기존의 예외 중 하나를 사용하여 사용자 정의 예외 것을 수정해야 경우) 오류가 컨트롤러 메서드 외부에서 처리되도록 (별도의 고려 사항, 좋은 방법으로 간주).

그렇지 않은 경우 컨트롤러 메서드에서 직접 응답을 설정할 수 있습니다.

그래서 두 경우 모두에서 당신과 같이, HttpServletResponsesendError 방법을 사용할 수 있습니다 :

// your controller (or exception) method 
    try { 
     response.sendError(HttpStatus.FORBIDEN.value(), "My custom error message") 
     } catch (IOException e) { 
    // handle if error could not be sent 
     } 
    } 

이 원하는 HttpStatus에 대한 응답으로 문자열을 인쇄합니다.

또한, 여기에 처리 봄 예외에 대한 몇 가지 '명곡 -하지만 - 골디'정보가 here

+0

THanks. JUnit 테스트 코드에서이를 어떻게 확인합니까? 귀하의 코드에 넣어 및 디버깅하는 동안 실행 점점 볼 수 있지만 "Assert.assertEquals ("적절한 오류 메시지를 반환하지 못했습니다. ", errorMsg, result.getResponse(). getContentAsString());" "result.getResponse(). getContentAsString()"이 비어 있다고 불평하지 않습니다. – Dave

+0

@Dave @ RestController'를 사용하는 경우 JSON 응답을 읽습니다. 그래서'mockMvc.perform (.....) .andExpect (content(). contentType (MediaType.APPLICATION_JSON)) .andExpect (jsonPath ("$. error.message"). "));'우편 배달부 등을 통해 전화를 걸어 json 구조를 볼 수 있습니다. –

관련 문제