IllegalStateException in servlets

Hi,

When do i get IllegalStateException in servlets.

What it means by trying to write to the output stream (response) after the response has been committed by  server. What it means by committing response and uncommitting response. cannot i send uncommitted response. please advise
LVL 7
gudii9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

rrzCommented:
cannot i send uncommitted response
No. A response is committed when its status code
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes   
and its response headers
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_Headers   
are written to client.  
When do i get IllegalStateException in servlets.

An IllegalStateException will be thrown when
the method getOutputStream is called after calling the getWriter method

the method getWriter is called after calling the getOutputStream method

the method setBufferSize is called after content has been written to client

the method reset is called after the response is committed
the method sendError is called after the response is committed
the method sendRedirect is called after the response was committed or if a partial URL is given and cannot be converted into a valid URL
What it means by trying to write to the output stream (response) after the response has been committed by  server.
That is not a problem. You can keep on writing. If you use the method setContentLength, then you could set a limit.  You can't write after calling the sendError or sendRedirect method.
0
gudii9Author Commented:
where do i read more on this topic. please advise
0
rrzCommented:
where do i read more on this topic
 I could not find any resources.  I just read the API.
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

rrzCommented:
I found time to write demonstration Servlet.
package rrz;
import java.io.IOException;
import javax.servlet.http.*;
import java.io.PrintWriter;
public class Commit extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { 
    PrintWriter writer = response.getWriter();  
    response.setContentType("text/plain");
	boolean before = response.isCommitted();
	// Flush buffer. This will send status code and headers to client.
	response.flushBuffer(); // Buffer is empty.
	boolean after = response.isCommitted();	// No content sent yet.
	writer.write("Content sent: Committed before = " + before + " Committed after = " + after);
  }
}

Open in new window

Output:
Content sent: Committed before = false Committed after = true
0
gudii9Author Commented:
package rrz;
import java.io.IOException;
import javax.servlet.http.*;
import java.io.PrintWriter;
public class ResponseCommitServlet extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { 
    PrintWriter writer = response.getWriter();  
    response.setContentType("text/plain");
	boolean before = response.isCommitted();
	// Flush buffer. This will send status code and headers to client.
	response.flushBuffer(); // Buffer is empty.
	boolean after = response.isCommitted();	// No content sent yet.
	writer.write("Content sent: Committed before = " + before + " Committed after = " + after);
  }
}

Open in new window


when i run above example getting error 404.

Please advise
0
gudii9Author Commented:
when i create dynamic web project and copied youservlet eclpse complaing no servet jar etc. I wonder why eclipse do not put jars like servlets.jar which are minimum for dynamic web project right. To run a simple servlet web application is such a time consuming process where i have to download all the proper version jars and put in lib folder then go to build path and set the classpahts.

Is there is simple example on running simple servlet and then replace with your servlet(may be using maven also fine if that is faster)
Please advise
0
gudii9Author Commented:
is there is a link with simple example and 'source code to download' which i can directly import to eclipse to run right away. please advise
0
gudii9Author Commented:
i checked this link
http://www.servlets.com/jservlet2/examples/

i am not able to import the zip and there are no jar files in each chapter once i unzip.
i checked below link
http://www.tutorialspoint.com/servlets/servlets-first-example.htm

there is no source code with required jar to import and run examples to eclipse with tomcat.
please advise
0
rrzCommented:
Is there is simple example on running simple servlet
I just use a stand alone Tomcat on my desktop.
0
gudii9Author Commented:
ok.

Looks like this link has downloadable source code archive file which i am able to import to eclipse directly
http://www.srccodes.com/p/article/3/Tomcat-Hello-World-Servlet-using-Eclipse-IDE
0
gudii9Author Commented:
package com.srccodes.example;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWorld() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter printWriter  = response.getWriter();
		printWriter.println("<h1>Hello World!</h1>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Open in new window


above helloworld servlet worked perfect.

But below code not running

package com.srccodes.example;
import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import java.io.PrintWriter;

@WebServlet("/Commit")
public class ResponseCommitServlet extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { 
    PrintWriter writer = response.getWriter();  
    response.setContentType("text/plain");
	boolean before = response.isCommitted();
	// Flush buffer. This will send status code and headers to client.
	response.flushBuffer(); // Buffer is empty.
	boolean after = response.isCommitted();	// No content sent yet.
	writer.write("Content sent: Committed before = " + before + " Committed after = " + after);
  }
}

Open in new window


i am giving url similar to HelloWorld as

http://localhost:8080/HelloWorldServlet/Commit

I am getting 404.
Please advise
0
gudii9Author Commented:
http://localhost:8080/HelloWorldServlet/HelloWorld

Above works fine not the Commit Servlet you posted for me some reason?
0
gudii9Author Commented:
running simple servlet takes around 1 hour time in eclipse.
I wonder what ae advantages of intelleJ IDE you are using?
0
rrzCommented:
http://localhost:8080/HelloWorldServlet/Commit
Is HelloWorldServlet the name of your web app?
0
gudii9Author Commented:
package com.srccodes.example;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWorld() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*response.setContentType("text/html");
		PrintWriter printWriter  = response.getWriter();
		printWriter.println("<h1>Hello World!</h1>");*/
		 PrintWriter writer = response.getWriter();  
		    response.setContentType("text/plain");
			boolean before = response.isCommitted();
			// Flush buffer. This will send status code and headers to client.
			response.flushBuffer(); // Buffer is empty.
			boolean after = response.isCommitted();	// No content sent yet.
			writer.write("Content sent: Committed before = " + before + " Committed after = " + after);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Open in new window

I pasted the new code in the old servlet  which worked fine and gave output

Content sent: Committed before = false Committed after = true
0
gudii9Author Commented:
I got before which is false

after how is it true

     boolean before = response.isCommitted();
                  // Flush buffer. This will send status code and headers to client.
                  response.flushBuffer(); // Buffer is empty.
                  boolean after = response.isCommitted();      // No content sent yet.

commit is on client or server side.

why the flushBuffer sens status code, header to client which seems committing response.

Please advise
0
rrzCommented:
running simple servlet takes around 1 hour time in eclipse.
Wow! That is bad.
I wonder what ae advantages of intelleJ IDE you are using?
I don't use intelleJ . I just use Tomcat without an IDE.  
But I can fire up my Eclipse and go through the necessary steps.
0
rrzCommented:
commit is on client or server side.
It is on server side. Once the server tells the client what it is going to do, it can't change it's mind.
0
rrzCommented:
why the flushBuffer sens status code, header to client which seems committing response.
I am just quoting the API. Look at  
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletResponse.html#flushBuffer()
0
gudii9Author Commented:
flushBuffer

void flushBuffer()
                 throws java.io.IOException
Forces any content in the buffer to be written to the client. A call to this method automatically commits the response, meaning the status code and headers will be written.
Throws:
java.io.IOException
See Also:
setBufferSize(int), getBufferSize(), isCommitted(), reset()
so buffer is also on the server right?
what is exact meaning of buffer (some data that is not useful?)
0
rrzCommented:
what is exact meaning of buffer
It is just a temporary place to store data that will be sent to client. This gives the server some flexibility. It can change it's mind and call reset method. It can call reset only before response is committed.
so buffer is also on the server right?
Yes.
A response buffer allows a servlet to write some amount of output with a guarantee that the response won't be immediately committed. If the servlet finds an error, the status code and headers can still be changed so long as the buffer has not been flushed.
In my code that I posted, the default status code and headers were already in the buffer(the servlet container put them there) when I called the flushBuffer method. "Flush"  means that whatever was in the buffer was sent to the client.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.