开发者

Servlet and error conditions

开发者 https://www.devze.com 2023-01-08 02:13 出处:网络
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)

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 开发者_Python百科throw ServletException?


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);
}  


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消