Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

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
Avatar of rrz
rrz
Flag of United States of America image

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.
Avatar of gudii9

ASKER

where do i read more on this topic. please advise
where do i read more on this topic
 I could not find any resources.  I just read the API.
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
Avatar of gudii9

ASKER

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
Avatar of gudii9

ASKER

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
Avatar of gudii9

ASKER

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
Avatar of gudii9

ASKER

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
Is there is simple example on running simple servlet
I just use a stand alone Tomcat on my desktop.
Avatar of gudii9

ASKER

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
Avatar of gudii9

ASKER

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
Avatar of gudii9

ASKER

http://localhost:8080/HelloWorldServlet/HelloWorld

Above works fine not the Commit Servlet you posted for me some reason?
Avatar of gudii9

ASKER

running simple servlet takes around 1 hour time in eclipse.
I wonder what ae advantages of intelleJ IDE you are using?
http://localhost:8080/HelloWorldServlet/Commit
Is HelloWorldServlet the name of your web app?
Avatar of gudii9

ASKER

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
Avatar of gudii9

ASKER

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
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.
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.
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()
Avatar of gudii9

ASKER

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?)
ASKER CERTIFIED SOLUTION
Avatar of rrz
rrz
Flag of United States of America 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