October 10, 2012

Responce once commited, any subsequent redirect operations will throw an IllegalStateException?

public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
String dbValue = getValueFromDB ();
if (dbValue == null) response.sendError (HttpServletResponse.SC_NOT_FOUND, "DB Lookup Failed");
response.sendRedirect ("Form.jsp");
}

Question:
Consider the following code snippet of above servlet code.
If the getValueFromDB () method returns null , which of the following statements are true?
(A) The code will work without any errors or exceptions
(B) An IllegalStateException will be thrown
(C) A NullPointerException will be thrown
(D) An IOException will be thrown

The correct answer(s):
(B) An IllegalStateException will be thrown
Explanation:
When the sendError() API is called, the response is considered committed and should not be written to
subsequently. Once the response is considered committed, any subsequent redirect operations will throw an
IllegalStateException.
In this above servlet code, the sendError() is invoked when the dbValue is null, which will cause the response to be
committed. Hence, the subsequent response.sendRedirect () method will then cause an IllegalStateException to
be thrown.
Reference: http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletResponse.html

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts