且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从spring servlet HTTP响应中删除Content-Length和Transfer-Encoding标头

更新时间:2022-04-26 23:27:06

您可以直接写入HttpServletResponse的OutputStream.如果愿意,Spring会给您HttpServletResponse(和HttpServletRequest),只需将其添加到方法签名中即可.

You could write directly to the HttpServletResponse's OutputStream. Spring will give you the HttpServletResponse (and the HttpServletRequest) if you want it, simply by adding it to your method signature.

这样,您可以(大部分)完全控制标题.您可能需要自己创建JSON,但这通常很简单.例如...

This way you have (mostly) full control of headers. You would probably need to create the JSON yourself, but it's usually quite simple. For example...

private ObjectMapper mapper = new ObjectMapper();

@RequestMapping(value = "/getStuff", method = RequestMethod.GET)
public void getStuff(HttpServletResponse httpServletResponse) throws Exception {
    try {
        httpServletResponse.setHeader("Pragma","public");
        httpServletResponse.setHeader("Expires","0");
        httpServletResponse.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
        httpServletResponse.setHeader("Cache-Control","public");
        OutputStream outputStream = httpServletResponse.getOutputStream();
        try {
            mapper.writeValue(outputStream, myObject);
        } finally {
            outputStream.close();
        }

这似乎不太优雅,但是通过使用@ResponseBody,您可以方便地完成创建响应的所有艰苦工作.但是,如果它没有按照您的意愿创建响应,则可以退后一步,然后使用HttpServletResponse手动"完成该操作.

This might not seem elegant, but by using @ResponseBody you are using that as a convenience to do all the hard work in creating the response. But if it is not creating the response as you would like it, you can take a step back and do it "manually" using HttpServletResponse.