• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1769
  • Last Modified:

org.apache.jasper.JasperException: getOutputStream() has already been called for this response

Hi,

I have a JSP page that serves data to our client. I have learned that this is actually a bad design. Servlet should be the way to go for this. But this is a legacy app so that the JSP must stay, at least for a while.

Below is some code snippet for the app.

I found that if I changed something in the JSP page, it will throw exception like this below:
org.apache.jasper.JasperException: getOutputStream() has already been called for this response
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:460)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:367)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

I read somewhere that JSP designed by default to return text. If I want to send out zip files, then trying to get output stream, obviously it raises a conflict of interest.

Sometimes it recovers by itself, but today I saw the exception doesn't go away.

That's why I'm confused why sometimes it becomes ok, sometimes it doesn't.

Can someone please advise how should I solve this problem?

I've been using JSP for a while but pretty new about servlets itself.
.....
.....
String filename = utility.getZipFileLocation(user, username, market, feed);
 
File myFile = new File(getServletContext().getRealPath(filename)); 
java.util.Date myFileDate = new java.util.Date(myFile.lastModified());
TimeZone tz = TimeZone.getTimeZone("GMT:00");
SimpleDateFormat dfGMT = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
dfGMT.setTimeZone( tz ); 
 
BufferedInputStream in = new BufferedInputStream(getServletContext().getResourceAsStream(filename));
	
response.setContentType(getServletContext().getMimeType(filename));
response.setHeader ("Content-Disposition", "attachment;filename=" + filename.replaceFirst(".+/(.+)", "$1"));
response.setHeader("Last-Modified", dfGMT.format(myFileDate));	
		
ServletOutputStream servletOutputStream = response.getOutputStream();
byte[] buffer = new byte[4 * 1024];
 
int data;
while((data = in.read(buffer)) != -1)
{
servletOutputStream .write(buffer, 0, data);
}
servletOutputStream .flush();		
servletOutputStream .close();
.....
.....

Open in new window

0
rnicholus
Asked:
rnicholus
  • 9
  • 5
  • 4
3 Solutions
 
rrzCommented:
The code you posted is servlet code. Did you want us to look at the JSP  ?  If so, then please post it.
Here is a link that might help you in your servlet code.  
http://www.experts-exchange.com/Web/Web_Languages/JSP/Q_20842012.html
0
 
rrzCommented:
If that is your JSP, then show us the complete page.
0
 
rnicholusAuthor Commented:
hi, thanks for your reply. here's the JSP.
<jsp:useBean id="utility" class="beans.UtilityBean" scope="request"/>
<%@ page errorPage="errorPage.jsp" %>
<%@ page import="java.sql.*, java.text.*, java.util.*, java.io.*" %>
<%@ include file="setting.jsp" %>
 
<%
	//////////////////////////////////////////////////
	// 1. Some variables declaration.
	//////////////////////////////////////////////////
	// Key is constructed from username, password, and market requested.
	String key = "";	String user = "";	String password = "";	String market = "";	
 
	String feed = "Z";	String username = request.getRemoteUser(); 
 
	//////////////////////////////////////////////////
	// 2. Check for the key sent by user.
	//////////////////////////////////////////////////
	if ( request.getParameter("key") == null )
	{
		response.sendRedirect("invalidAccess.jsp?error=Pleas specify a key");
		return;
	}
	else
	{
		key = request.getParameter("key");
		String[] tokens = key.split(",");
		// Key should have a length of 3. It is constructed from 
		// username, password, and market requested.
		if ( tokens.length != 2 )
		{
			response.sendRedirect("invalidAccess.jsp?error=There is a problem");
			return;
		}
		else
		{
			user = tokens[0];
			password = "test";
			market = tokens[1];
		}
	} 
%>
 
<%
	if ( username == null )
	{
		response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Unauthorized");
	}	
	else
	{
 
	//////////////////////////////////////////////////
	// 3. If the key is okay, then try to 
	//    check the login using LMS system.
	//    In this case, it's the LoginBean.java.
	//////////////////////////////////////////////////
	String loginResult = utility.login(user, username, password, market, feed);
 
	if ( !loginResult.equals("OK") )
	{
		// Does not "return;" since it needs do do "utility.closeConnection();" below
		response.sendRedirect("invalidAccess.jsp?error=" + loginResult);
	}
	else
	{
		//////////////////////////////////////////////////
		// Get the zip file.
		//////////////////////////////////////////////////
		String filename = utility.getZipFileLocation(user, username, market, feed);
 
		File myFile = new File(getServletContext().getRealPath(filename)); 
 
		java.util.Date myFileDate = new java.util.Date(myFile.lastModified());
       	TimeZone tz = TimeZone.getTimeZone("GMT:00");
         	SimpleDateFormat dfGMT = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
           	dfGMT.setTimeZone( tz ); 
 
		BufferedInputStream in = new BufferedInputStream(
			getServletContext().getResourceAsStream(filename));
	
		response.setContentType(getServletContext().getMimeType(filename));
		response.setHeader ("Content-Disposition", "attachment;filename=" + filename.replaceFirst(".+/(.+)", "$1"));
		response.setHeader("Last-Modified", dfGMT.format(myFileDate));	
		
		ServletOutputStream servletOutputStream = response.getOutputStream();
    	byte[] buffer = new byte[4 * 1024];
 
    	int data;
    	while((data = in.read(buffer)) != -1)
    	{
    		servletOutputStream .write(buffer, 0, data);
    	}
    	servletOutputStream .flush();		
    	servletOutputStream .close();
    	
	}
 
	utility.closeConnection();
 
	} // end else if ( username != null )
%>

Open in new window

0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
objectsCommented:


        int data;
        while((data = in.read(buffer)) != -1)
        {
                servletOutputStream .write(buffer, 0, data);
        }
        servletOutputStream .flush();    // you shouldn't need this        
        servletOutputStream .close();    // or this

       // try adding this

       out.clear();
       out = pageContext.pushBody();

0
 
rrzCommented:
><%@ include file="setting.jsp" %>
Please show us  setting.jsp  too.  

First try object's idea, then if that doesn't work , try   using   the following for the last part of your page.

...
          int data;
          while((data = in.read(buffer)) != -1)
          {
                servletOutputStream .write(buffer, 0, data);
          }
      }
      utility.closeConnection();
                 if(out != null) return;
      } // end else if ( username != null )
%>

One more idea.  If you still get the same error message when trying our ideas, then try adding  to the page directive   like the following  
<%@ page errorPage="errorPage.jsp"  autoflush="false"%>  
and see what error message you get with that.  
0
 
rnicholusAuthor Commented:
Both object's and rrz@871311 suggestion doesn't work.

Also I tried the autoflush:
org.apache.jasper.JasperException: /myPage.jsp(2,0) Page directive has invalid attribute: autoflush

rrz@871311.. sorry the setting.jsp is not needed. I removed it. It only consists of what's in the code snippet.



<%
	String VARIABLE_NAME = 
		"/directoryA/directoryB/....";
%>

Open in new window

0
 
objectsCommented:
also try removing all whitspace from the page

eg. line 42

%>
 
<%

0
 
rrzCommented:
>Also I tried the autoflush:  
Sorry that should be   autoFlush="false"
But, if you took out setting.jsp, then that idea won't get us anywhere.
Try object's latest idea.  To be clearer, he is suggesting something like the format below here.  
That way you will hopefully avoid any out.write()  statements.  Take a look at the .java file  that is the translation of your JSP file, before and after you make those changes.  Look in Tomcat's work folder for those.
<jsp:useBean id="utility" class="beans.UtilityBean" scope="request"/><%@ page errorPage="errorPage.jsp" import="java.sql.*, java.text.*, java.util.*, java.io.*" %><%
 put your scriptlet content here  
%>   

Open in new window

0
 
rnicholusAuthor Commented:
Guys,

Sorry. Haven't got a chance to get back to this until today.

> That way you will hopefully avoid any out.write()  statements.
This doesn't seem to make a difference.

These are some updates of what I found:
1. I found that in one case apparently, I point to the file that doesn't exist and it gives me that error output somehow.
2. In other case, the file is there but still gives me that error message. I point to other files with the same JSP. It works just fine.

I'm really confused especially about the second case.
And I'm wondering whether I'm just lucky or there could be other potential problem besides file doesn't exist/ bad files?

Thanks for the ongoing help, guys.
0
 
objectsCommented:
the error will occur if your page attempts to write anything to the output stream as you have made a call to getOutputStream()
0
 
rnicholusAuthor Commented:
objects,

do you mean that JSP designed by default to return text. If I want to send out zip files, then trying to get output stream, obviously it raises a conflict of interest.

but why it works sometimes and not the others?

and i'm confused about the two cases that i found:
1. I found that in one case apparently, I point to the file that doesn't exist and it gives me that error output somehow.
2. In other case, the file is there but still gives me that error message. I point to other files with the same JSP. It works just fine.
0
 
rnicholusAuthor Commented:
Is it possible that it's also related to file size. I have 101 feeds with different files. It looks like the files with small size are giving problems.
0
 
objectsCommented:
yes jsp's are designed to return text, but the problem here is that getOutputStream() is only intended to be called once. As soon as there is anything in the jsp that needs to be output will result iun it being called again (in addition to your explicit call)
Have a look at the generated java source to see whats getting output.

0
 
rnicholusAuthor Commented:
I saw this being put in the Java source by default: [CODE]response.setContentType("text/html");[/CODE]

Someone suggested to put this (similar to object's suggestion) to avoid the getOutputStream() error
[CODE]out.clearBuffer();[/CODE]
Seems to work. I don't see the previous problem where big files ok, small files not.

But I'm actually not sure why it works now and
I'm worried I'm still missing something then it will break again sometime in future?
What do you think?

Thanks.
0
 
rrzCommented:
>out.clearBuffer();
objects suggested that in his first post.
0
 
rnicholusAuthor Commented:
rrz@871311,

objects suggested the two lines in the code snippet.
i'm not sure the differences actually? can you please advise?

thanks
out.clear();
out = pageContext.pushBody(); 

Open in new window

0
 
rnicholusAuthor Commented:
I just realized that probably I should post the follow-up questions in another post.
I'll give points for the solution.
0
 
rnicholusAuthor Commented:
out.clearBuffer() seems to solve the problem.
I have some follow-up questions that I will post in other threads later.
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 9
  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now