Link to home
Start Free TrialLog in
Avatar of rnicholus
rnicholus

asked on

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

Avatar of rrz
rrz
Flag of United States of America image

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.  
https://www.experts-exchange.com/questions/20842012/How-to-show-file-download-dialog-box-in-IE-6-0.html
If that is your JSP, then show us the complete page.
Avatar of rnicholus
rnicholus

ASKER

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

ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

also try removing all whitspace from the page

eg. line 42

%>
 
<%

>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

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.
the error will occur if your page attempts to write anything to the output stream as you have made a call to getOutputStream()
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.
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.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
>out.clearBuffer();
objects suggested that in his first post.
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

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