Why do I get the error java.lang.IllegalStateException: Header already sent ?
Created May 7, 2012
An HTTP repsonse message is composed as follows: an HTTP reponse code (something like "HTTP/1.1 200 OK") followed by zero or more headers (something like "ContentType: text/html") followed by the repsonse contents.
This allows a server to send the headers to the client before sending the response contents. This way the client can determine some meta data about the repsonse (for example what the type of the content is).
This means that as soon as the first byte of repsonse contents is written the reponse goes into a state where headers can't be set. Trying to do so, results in an IllegalStateException.
So the wrong way is:
The right way is:
OutputStream out =
response.getOutputStream();
out.writeln("Hello...");
out.flush();
response.setContentType("text/html");
response.setContentType("text/html");
OutputStream out =
response.getOutputStream();
out.writeln("Hello...");
out.flush();