?
Solved

IllegalStateException in servlets

Posted on 2014-08-06
21
Medium Priority
?
321 Views
Last Modified: 2014-08-10
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
0
Comment
Question by:gudii9
  • 12
  • 9
21 Comments
 
LVL 28

Expert Comment

by:rrz
ID: 40245376
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
 
LVL 7

Author Comment

by:gudii9
ID: 40250232
where do i read more on this topic. please advise
0
 
LVL 28

Expert Comment

by:rrz
ID: 40251042
where do i read more on this topic
 I could not find any resources.  I just read the API.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 28

Expert Comment

by:rrz
ID: 40251388
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
 
LVL 7

Author Comment

by:gudii9
ID: 40251411
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
 
LVL 7

Author Comment

by:gudii9
ID: 40251413
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
 
LVL 7

Author Comment

by:gudii9
ID: 40251415
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
 
LVL 7

Author Comment

by:gudii9
ID: 40251416
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
 
LVL 28

Expert Comment

by:rrz
ID: 40251417
Is there is simple example on running simple servlet
I just use a stand alone Tomcat on my desktop.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40251420
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
 
LVL 7

Author Comment

by:gudii9
ID: 40251423
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
 
LVL 7

Author Comment

by:gudii9
ID: 40251426
http://localhost:8080/HelloWorldServlet/HelloWorld

Above works fine not the Commit Servlet you posted for me some reason?
0
 
LVL 7

Author Comment

by:gudii9
ID: 40251428
running simple servlet takes around 1 hour time in eclipse.
I wonder what ae advantages of intelleJ IDE you are using?
0
 
LVL 28

Expert Comment

by:rrz
ID: 40251429
http://localhost:8080/HelloWorldServlet/Commit
Is HelloWorldServlet the name of your web app?
0
 
LVL 7

Author Comment

by:gudii9
ID: 40251430
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
 
LVL 7

Author Comment

by:gudii9
ID: 40251431
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
 
LVL 28

Expert Comment

by:rrz
ID: 40251432
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
 
LVL 28

Expert Comment

by:rrz
ID: 40251435
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
 
LVL 28

Expert Comment

by:rrz
ID: 40251442
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
 
LVL 7

Author Comment

by:gudii9
ID: 40251644
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
 
LVL 28

Accepted Solution

by:
rrz earned 2000 total points
ID: 40251842
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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month15 days, 12 hours left to enroll

850 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