如何将内容输出到HttpServletResponse缓冲区?

问题描述 投票:1回答:3

我正在使用Spring 4.3.8.RELEASE。我想为特定的Forbidden错误设置错误消息。我在控制器中有这个。 “response”的类型为“javax.servlet.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缓冲区的正确方法?

spring servlets junit httpresponse mockmvc
3个回答
2
投票

你永远不会把errorMsg写到outputbuffer

就像是

response.getWriter().write(errorMsg)

应该解决这个问题


0
投票

您可以使用响应实体

@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
投票

一个好处是throw一个自定义异常传递HttpServletResponse作为参数或使用一个已经存在的异常(如果它服务于你的用例),这样就可以在控制器方法之外处理错误(单独的关注,被认为是好的实践)。

如果没有,您可以直接在控制器方法中设置响应。

所以在这两种情况下你都可以使用HttpServletResponses sendError方法,如下所示:

// 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的响应。

另外,这里有一些关于Spring Exception处理here的'oldie-but-goldie'信息

© www.soinside.com 2019 - 2024. All rights reserved.