views:

49

answers:

3

Hello

I'm writing my first JAVA servlet and I have a question.

May be it's important to say that my servlet will be called from Google Web Toolkit (AJAX)

First thing that I do is to create PrintWriter and start to write in it my JSON output

PrintWriter out = response.getWriter();
...
out.println("[");
out.println("  {");
out.println("    \"validation\" : {");
...

but what will happened if meanwhile I get an error condition?

What is the right way to return an error to client? (AJAX client)

Do I have to buffer my output (HOW?) and return error as JSON (instead of output) or I have to throw ServletException?

+1  A: 

See the HTTP status codes. You can use HttpServletResponse.setStatus to set the response state (note also the constants defined by that class).

McDowell
+2  A: 

As @McDowell says, the correct way to deal with an error during request handling in a servlet is to set an HTTP status code in the response object.

But there is a catch.

The HTTP status code is actually passed in the first line of the HTTP response. And that gets written when the response is "committed", which typically happens when you call response.getOutputStream() or response.getWriter(). After that, you cannot change the status code.

The way to deal with it is to do one of the following:

  • Code your application so that errors don't happen during the generation of the response body.
  • Generate the response body to a buffer of some kind, and only open the response output stream / reader when you've built it completely. If there are errors during the body generation, you can set the HTTP status code and (if appropriate) send an alternative body containing an error message.
Stephen C
Can you help me with example for buffering and how to export it in response?
ju
@ju - see @BalusC's answer.
Stephen C
+2  A: 

Just build the string in memory using for example StringBuilder. Do not write any character to the response yet until you're finished building the string. That's "buffering".

StringBuilder builder= new StringBuilder();
builder.append("[");
builder.append("  {");
builder.append("    \"validation\" : {");
// ...

// When finished:
response.getWriter().write(builder.toString());

When something fails in meanwhile, either throw ServletException (which will end up in a server default error page with status code 500), or use HttpServletResponse#sendError() to send a more specific error status. But generally, status code 500 is enough sign for XMLHttpRequest client that something failed at the server side.

try {
    // Build and write JSON.
} catch (Exception e) {
    throw new ServletException(e);
}  
BalusC
Is this also OK?ByteArrayOutputStream outBuf = new ByteArrayOutputStream();PrintStream out = new PrintStream(outBuf, true, "UTF8");...outBuf.writeTo(response.getOutputStream());
ju
Let's say: Wrong tools for the job. It'll work, but it's not the right way.
BalusC