Why I can still send data after the response is co

2019-04-17 13:53发布

I use the following REST handler to transfer a file to client.

I deliberately called response.flushBuffer() in hope that I should be blocked from writing to the response since it is already committed. And I expect client will not receive the full file.

But the whole file still gets sent to client. And no exception about Response Already Committed is thrown.

Why?

My code:

@RestController
public class ChunkedTransferAPI {

    @Autowired
    ServletContext servletContext;

    @RequestMapping(value = "bootfile.efi", method = { RequestMethod.GET, RequestMethod.HEAD })
    public void doHttpBoot(HttpServletResponse response) {

        String filename = "/realbootfile.efi";
        try {
            ServletOutputStream output = response.getOutputStream();

            InputStream input = servletContext.getResourceAsStream(filename);
            BufferedInputStream bufferedInput = new BufferedInputStream(input);
            int datum = bufferedInput.read();
            while (datum != -1) {
                output.write(datum);
                datum = bufferedInput.read();
                response.flushBuffer(); // <======= HERE
            }
            //output.flush();
            output.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

1条回答
女痞
2楼-- · 2019-04-17 14:46

A response is "committed" when the header has been sent, and it means that changes to response headers cannot be honored. It doesn't stop you from writing the response body.

查看更多
登录 后发表回答