代码之家  ›  专栏  ›  技术社区  ›  Dave

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

  •  1
  • Dave  · 技术社区  · 7 年前

    我使用的是Spring 4.3.8。释放。我想为特定的禁止错误设置错误消息。我的控制器里有这个。“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缓冲区的正确方法是什么?

    3 回复  |  直到 7 年前
        1
  •  2
  •   Philippe Marschall    7 年前

    你从不写信 errorMsg output buffer .

    类似于

    response.getWriter().write(errorMsg)
    

    应该解决问题

        2
  •  0
  •   Amr Alaa    7 年前

    您可以使用响应实体

    @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

        3
  •  0
  •   Urosh T. Leo Zhao    7 年前

    一件好事是 throw 自定义异常传递 HttpServletResponse 作为参数或使用已经存在的异常之一(如果它服务于您的用例),以便在控制器方法之外处理错误(单独关注,被视为良好做法)。

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

    所以在这两种情况下,您都可以使用 HttpServletResponse s 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异常处理的“老生常谈”信息 here