Solved

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

Posted on 2009-04-09
18
1,706 Views
Last Modified: 2012-05-06
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
Comment
Question by:rnicholus
  • 9
  • 5
  • 4
18 Comments
 
LVL 27

Expert Comment

by:rrz
Comment Utility
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
 
LVL 27

Expert Comment

by:rrz
Comment Utility
If that is your JSP, then show us the complete page.
0
 

Author Comment

by:rnicholus
Comment Utility
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
 
LVL 92

Accepted Solution

by:
objects earned 450 total points
Comment Utility


        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
 
LVL 27

Assisted Solution

by:rrz
rrz earned 50 total points
Comment Utility
><%@ 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
 

Author Comment

by:rnicholus
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
also try removing all whitspace from the page

eg. line 42

%>
 
<%

0
 
LVL 27

Expert Comment

by:rrz
Comment Utility
>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
 

Author Comment

by:rnicholus
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 92

Expert Comment

by:objects
Comment Utility
the error will occur if your page attempts to write anything to the output stream as you have made a call to getOutputStream()
0
 

Author Comment

by:rnicholus
Comment Utility
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
 

Author Comment

by:rnicholus
Comment Utility
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
 
LVL 92

Assisted Solution

by:objects
objects earned 450 total points
Comment Utility
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
 

Author Comment

by:rnicholus
Comment Utility
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
 
LVL 27

Expert Comment

by:rrz
Comment Utility
>out.clearBuffer();
objects suggested that in his first post.
0
 

Author Comment

by:rnicholus
Comment Utility
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
 

Author Comment

by:rnicholus
Comment Utility
I just realized that probably I should post the follow-up questions in another post.
I'll give points for the solution.
0
 

Author Closing Comment

by:rnicholus
Comment Utility
out.clearBuffer() seems to solve the problem.
I have some follow-up questions that I will post in other threads later.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now