Buffer

<%
for(int i=0;i<100;i++){
 System.out.println("Hello World <br>");
}

<jsp:forward page="Two.jsp"/>
In the above example, if we execute the above piece of code, we get the output from Two.jsp. But if we use "i<1000", the container fails. This is the problem with jsp:forward. To improve the performance of network server and client, buffering technique will be used by the jsp writer to reduce the network traffic.
<%@ page buffer="1kb" %>

<%
for(int i=0;i<100;i++){
 System.out.println("Hello World <br>");
}

<jsp:forward page="Two.jsp"/>
When we send a request to the above jsp file, initially 1024(1kb) bytes of memory will be allocated and the content that is generated by the jsp will be collected in the buffer (In this example the total amount of content generated by the jsp is less than the size of the buffer) and then it will be sent to the client at once.
If we change i value to less than 200 and then send a request to the above jsp page 1kb of memory will be allocated as buffer. The jsp page generates more than 1kb of data. In this case initially 1024 bytes will be collected in the buffer. After this the buffer will be flushed (The content will be sent to the client). After this the remaining amount of data that is 2000-1024 will be collected in the buffer and it will be sent to the client.
Interview Question: What is buffer over flow and how do you solve the problem?
Answer:
<%@ page buffer="10kb" %>
<%@ page autoFlush="false" %>

<%
for(int i=0;i<20000;i++){
 System.out.println("Hello World <br>");
}

<jsp:forward page="Two.jsp"/>
When a request is sent to the above jsp page "10kb" of memory will be allocated. Then 10kb of output will be collected as we have used autoFlush="false" the buffer will not be flushed and the content generated by the jsp cannot be accomplished in the buffer. This condition is called "buffer overflow".
We can solve this problem by increasing the buffer size so that the whole content generated by the jsp can be accomodated in the buffer or we can use the autoFlush="true". autoFlush is by default is true.

No comments:

Post a Comment