简体   繁体   中英

http streaming using java servlet

I have a servlet based web application which produces two sets of data. One set of data in the webpage which is essential and other set which is optional. I would like to render the essential data as fast as possible and then stream the optional data. I was thinking of writing the essential data to the output stream of HttpServletRequest and then call HttpServletRequest.flushBuffer() to commit the response to the client, but do not return from the servlet code, but instead create the optional data , write that to the outputstream again and then return from servlet code. What are the things that could go wrong in this scheme ? Is this a standard practice to achieve this goal?

It makes somewhat sense to flush the response buffer directly between </head> and <body> so that the browser retrieves references to JS/CSS resources as fast as possible. It only doesn't make sense to do it in a servlet as it's the JSP who is supposed to be used to generate HTML.

</head>
<% response.flushBuffer(); %>
<body>

(that's one of the 0.01% cases where using a scriptlet is forgiveable as there's no tag which does that; only in EL 2.2 you could use ${pageContext.response.flushBuffer()} )

However, most servletcontainers by default already flush the buffer every 2KB and that'll surely cover the entire <head> on the average webapp. You can finetune the response buffer size in server configuration (refer server documentation for details) or on a per-JSP basis using as follows:

<%@page buffer="1kb" %>

Further, flushing the buffer halfway a HTML <body> makes little to no sense as you're dependent on the browser whether it would render a halfbaked HTML body or not. MSIE for example displays nothing until the </body> is arrived.

A completely different alternative is to use JS/Ajax to load the "optional" content asynchronously in the background when the page is completed loading. Eg (jQuery flavored):

$(function() {
    $("#somediv").load("somefragment.jsp");
});

See also:

I would do this instead :

  • return essential data as normal servlet + javascript to do Ajax calling for optional data. Then essential data will be shown with out wait the optional data.

so the html will look like this:

<html>
   <body>
        essential data
        <javascript to do ajax call>
        essential data
   </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM