This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Little Book of Impediments (e-book only) and have Tom Perry on-line!
See this thread for details.
Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why an ouput of file can stop a StackOverflow?

 
Yorck Zhou
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have gotten a strange web app:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class test extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException {
res.setContentType("text/plain;");
OutputStream os = res.getOutputStream();
byte [] bytearray = new byte[1024];
ServletContext context = getServletContext();
1InputStream is = context.getResourceAsStream("/files/data.txt");
2int bytesread=0;
3while( (bytesread=is.read(bytearray))!=-1 ){
4os.write (bytearray, 0, bytesread);
5}
6os.flush();
7is.close();
System.out.println("before the resquestDipatcher");
8RequestDispatcher rd = context.getRequestDispatcher("/test/test");
rd.forward(req, res);
System.out.println("after the requestDispatcher");
}
}
<web-app>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>test</servlet-class>
</servlet>
</web-app>
if i delete the line from 1-7, then a StackOverflowError will be thrown, but with these line on, the program will
run to line 8 and terminated "normally", can anyone tell me how it works?
 
Phil Rhodes
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
does the url you're forwarding to match the url of the servlet you're testing? It looks like it might, and if it does, you're creating a recursive call by doing that, hence the stack overflow.
Why adding in the other code prevents that, I don't know, unless maybe it's throwing an exception of it's own that's breaking the recursive cycle.
 
Phil Rhodes
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, duh, I get it now... you're trying to do a forward, after you've already committed the response. Therefore the forward fails, and hence no recursive call. Take out the stuff that writes to and closes the output stream, and the forward works, and you get a recursive call, and the resulting StackOverflowException...
 
Yorck Zhou
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank u, Phil. you are right. when i output the outputstream with the os.flush(), the response committed, but when the os.flush() line is commented, then a StackOverflow emgers immediately.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic