aspose file tools*
The moose likes Servlets and the fly likes IllegalStateException error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "IllegalStateException error" Watch "IllegalStateException error" New topic
Author

IllegalStateException error

Jeff Sunder
Ranch Hand

Joined: Jun 26, 2001
Posts: 47
I am getting this error when I try to forward a servlet to a jsp page. Let me explain what the servlet is doing. In the init(), the servlet creates an instance of a connection pool class(helper class). In the service(), the first thing is it checks to see if a cookie has been installed. If not, it forwards them to a login page, so that a cookie can be created and brings them back to the servlet. Then the servlet will perform a few sql queries which depend on the variables in the cookie. Then I throw the sql results in html table and put that table in a String variable. Then I forward from a servlet to another Jsp page and pass the string variables to display within that jsp. However, I am getting an IllegalStateException when I forward to the JSP that displays the results. Does any one give me some ideas on what I am doing wrong? Any help is appreciated.
Tony Alicea
Desperado
Sheriff

Joined: Jan 30, 2000
Posts: 3222
    
    5
Make sure you have not done any output to the client before forwarding.
Doesn't the rest of the error msg say "Response has already been committed" or something like that?


Tony Alicea
Senior Java Web Application Developer, SCPJ2, SCWCD
Jeff Sunder
Ranch Hand

Joined: Jun 26, 2001
Posts: 47
I don't think I have done any ouput to the client. I am forwarding to the JSP page from the servlet to display the sql result within the jsp. Here is the code, if any one can help me out I would greatly appreciate it.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
public class ProjectStatus extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";
ConnectionPool connPool = null;
public void init(ServletConfig config) throws ServletException {
super.init(config);
String jdbcDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
String dbURL = "jdbc dbc:ProjectsDb";

try {
connPool = new ConnectionPool(jdbcDriver, dbURL, "projects", "projects");
connPool.setInitialConnections(5);
connPool.setIncrementalConnections(5);
connPool.setMaxConnections(15);
connPool.setTestTable("Projects");
connPool.createPool();
}catch (Exception e) {
System.out.println("Error " +e);
}
} //close init()
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String userFirstName = "jeff";//(String)request.getAttribute("userFirstName");
String userLastName = "sunder";//(String)request.getAttribute("userLastName");
response.setContentType(CONTENT_TYPE);
PrintWriter out= response.getWriter();
String resultString = "";
String unassignedString="";
int rowCount=1;
try{
Connection dbConn = null;
dbConn = connPool.getConnection();
Statement stmt = dbConn.createStatement();
String getUserProjects = "Select * from projects where pl_first_name='"+userFirstName+"' and pl_last_name='"+userLastName+"'";
ResultSet rs = stmt.executeQuery(getUserProjects);
while (rs.next()) {
resultString+="<tr><td>"+rowCount+"</td><td><a href=\"ProjectDetails?project="+rs.getString("projects_id")+"\">"+rs.getString("project_name")+"</a></td>\n"+
"<td>"+rs.getString("project_reason")+"</td><td align=\"middle\">"+rs.getString("status")+"</td>\n"+
"<td>"+rs.getString("submitter_first_name")+" "+rs.getString("submitter_last_name")+"</td>\n"+
"<td>"+rs.getString("department")+"</td><td>"+rs.getString("pl_first_name")+" "+rs.getString("pl_last_name")+"</td></tr>\n";
rowCount++;
}
String getUnassignedProjects = "Select * from projects where status='unassigned';";
ResultSet rs2 = stmt.executeQuery(getUnassignedProjects);
while (rs2.next()) {
unassignedString += "<tr><td>"+rowCount+"</td><td><a href=\"ProjectDetails?project="+rs.getString("projects_id")+"\">"+rs.getString("project_name")+"</a></td>\n"+
"<td>"+rs.getString("project_reason")+"</td><td align=\"middle\">"+rs.getString("status")+"</td>\n"+
"<td>"+rs.getString("submitter_first_name")+" "+rs.getString("submitter_last_name")+"</td>\n"+
"<td>"+rs.getString("department")+"</td><td>"+rs.getString("pl_first_name")+" "+rs.getString("pl_last_name")+"</td></tr>\n";
}
}catch (Exception e) {
//out.println(e.getMessage());
}/*finally{
connPool.returnConnection();
}*/
request.setAttribute("userProjects", resultString);
request.setAttribute("unassignedProjects", unassignedString);
try{
RequestDispatcher d = request.getRequestDispatcher("../src/DisplayStatus.jsp");
d.forward(request, response);
}catch (ServletException sx) {
}

} //close service()
}
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

If you are setting cookies, you are commiting the headers on the response, so perhaps this is what is screwing things up. (Sorry, I didn't look at your code, but it's the first thing that came to mind from your original post)

A second strategy is not to forward, but 'include' the JSP. Including JSP's means that the servlet still maintains ultimate resonsibility for outputting the response. Forwarding means that the 'forwardee' is responsible.
[This message has been edited by Mike Curwen (edited July 23, 2001).]
Beksy Kurian
Ranch Hand

Joined: Jul 11, 2001
Posts: 254
remove the printwriter statement and try again
Beksy
Jeff Sunder
Ranch Hand

Joined: Jun 26, 2001
Posts: 47
Well I tried taking out the PrintWriter statement out, as well as, the SetContentType statement. But neither worked. I also tried changing it from a forward to an include, but I got the same error message. The table is outputting, but I am getting an error right before the table. This is the error:
Included servlet error: 500Location: /src/DisplayStatus.jspInternal Servlet Error:java.lang.IllegalStateException: Response has already been committed
I don't think that I have been trying to write to the HTTP header after it has been posted to the browser, but I could be overlooking something. What are some other reasons I get this error messgae?
[This message has been edited by Jeff Sunder (edited July 23, 2001).]
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

I've tried your code, and it works fine on Tomcat 3.2.2

Here is my code, edited greatly because I don't have your database.The JSP looks pretty simple:
In case you wonder, my directories look like this:
web-app-root
-- jsp
----- DisplayStatus.jsp
-- WEB-INF
----- classes
--------- servlets
-------------- ProjectStatus.class
----- web.xml

Inside web.xml, it looks like this:
I show you this for completeness, not because I don't think you know it.

So not sure what the problem is... perhaps try putting all of your code in the doGet method, and leave service alone. From the Servlet API--- Perhaps you are 'breaking' some feature of your servlet runner by touching this method?
[This message has been edited by Mike Curwen (edited July 23, 2001).]
Subbu Aswathanarayan
Ranch Hand

Joined: Jun 22, 2001
Posts: 73
hi Jeff,
just try this.this might solve ur problem.
compile ur code again after removing the PrintWriter and SetContentType statement and restart the servlet runner.then place the servlet class file in the appropriate directory and try running ur servlet.this has solved my problems many times(i use JRun on NT).
also avoid overriding the service method.do all ur stuff in either doGet or doPost.
do let us know if it worked.
Subbu


Subbu
Jeff Sunder
Ranch Hand

Joined: Jun 26, 2001
Posts: 47
I tried to replace my service method with a doPost method. But now I get this error:
Unable to open location: Could not connect to: http://localhost:8080/servlet/ProjectStatus3
I thought the doPost and doGet methods are called when you have an associated form. My servlet is somewhat of a controller. What it supposed to do is check if a cookie exists, if the cookie does not exists it takes them to a login form where the cookie gets created. Then control goes back to the servlet to perform the sql stuff.
I really need to get his working, any help is greatly appreciated.
Jeff Sunder
Ranch Hand

Joined: Jun 26, 2001
Posts: 47
Got the error in the previous post fixed. But I still get the same IllegalStateException error. The weird thing is that the table is being outputted correctly. The only thing is that I am getting that error. I even simplified my servlet to just query a database and then call the jsp page to post the results, but again that error occurs. So the only place where the response is committed is when I forward or inlcude the jsp page.
I did comment out the PrintWrite and setContentType lines and then restarted my servlet container, but that did not work either.
I'm in a real jam, any ideas? Thanks in advance
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

Yes, the doGet and doPost are called when an associated form is used...

If you have your method as post, then the doPost method of servletName is run.

But you can also invoke a servlet from an URL, without submitting a form, by 'faking' a get request by constructing the query string.

ie: http:// myserver.com/controllerServlet?page=1&id=3

So this would invoke the controllerServlet's doGet method, and the parameters available are page and id.

When you say "then control goes back to the servlet"... (from the login page)... how does it go back to the servlet? Is the login form submission's action parameter that servlet?
Jeff Sunder
Ranch Hand

Joined: Jun 26, 2001
Posts: 47
The way the controller servlet is intended to work is:
end user will click on the url which will lead them to the controller servlet. Then the servlet will determine if a cookie has been installed on the client. If not, it will forward to a login in page, where the cookie is created and then forward back to the controller servlet. The servlet will then perform several sql statements (based on the values of the cookie) and then will forward to a jsp page which will display the results of the sql statements. The error is occuring when I try to forward to the jsp page. For some reason, the jsp page displays the table with the sql results properly outputted, but right before the table, I am getting a IllegalStateException error.
My problem is, I don't know why I am getting this IllegalStateException error.
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

I'm not sure why you get the IllegalStateException, without seeing all of your code.

But here is code that does work. I've slightly modified your architecture.. partly because I don't know how to set cookies with servlets, and partly because you shouldn't need to... JSP/Servlets have session objects for just such a purpose, and because the session is implemented as a cookie, it amounts to the same thing.

Here then is a small application that work (too bad I couldn't attach the WAR file)
Login.htmlLoginServlet
**ProjectStatus.jsp is the same as before
**ProjectStatus servlet is modified
web.xml contains: And my file directory is as before, with the additional servlet class in the web-inf/classes directory and the additional html file off the appRoot

If you request http:// localhost:8080/appRoot/status and you are not logged in, the Status servlet forwards you to the login servlet. The login servlet assumes a successful login, and will then send you back to the status servlet (via another forward). The status servlet does its thing and then forwards you to the output jsp.

If you hit the login servlet first... then everything proceeds smoothly from successful login, to forwarding to status, to then forwarding to the output jsp.

Any subsequent attempts to access the status servlet, and you do not need to be redirected to the login servlet. (as long as you don't close your browser window).

This works on NT4 SP6, Tomcat 3.2.1, Netscape and IE.

Hope it helps.

[This message has been edited by Mike Curwen (edited July 25, 2001).]
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16305
    
  21

I haven't looked at the code in detail, but IllegalStateException often comes from the database code. I think you went down a blind alley on the cookie/header/http aspect.


Customer surveys are for companies who didn't pay proper attention to begin with.
Micah Kornfield
Greenhorn

Joined: Jul 23, 2001
Posts: 8
The illegalstateexception usually has something to do with your session variables. There are some good resources if you do a web search telling you what you can and cannot do with the session variable.
Good Luck
-MK


God help us if computers ever unite against us<BR>When computers get together to make decisions, they form a Beowulf cluster. When humans get together to make decisions, they form a comittee. Need I say more?<P>-- archnerd on slashdot
Jeff Sunder
Ranch Hand

Joined: Jun 26, 2001
Posts: 47
Can you provide some of those online resources ?
Johnson Samuel
Greenhorn

Joined: Jul 28, 2001
Posts: 4
Originally posted by Jeff Sunder:
Can you provide some of those online resources ?

hi,
if jsp
In the header set autoflush=true and buffer size to some higher value as default is just 8k..
if servlet
There are certain method setBufferSize()

regards
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: IllegalStateException error