views:

107

answers:

4

What is the correct way of terminating a servlet that doesn't return any data to the client?

The purpose of the servlet in question is to recive some data from an Ajax request and fire off a TCP message to a piece of hardware to tell it to change it's state.

Do you have to specify a response at all?

I've opted for getting a reference to the Output stream and closing it, is this correct?

Should I send back a "hey that worked" message?

+2  A: 

Your servlet is going to send the response headers with the status code and whatnot in any case, I don't see why you should output anything on top of that. :)

Rytmis
+1  A: 

In these situations I generally return a success message, i.e. something like (in JSON)

{ success: true }

I find it helps sometimes with debugging! I don't think there is a 'correct' response though, provided that your servlet returns a 200 response code (which I think they do unless you specify otherwise) then there is no problem.

Phill Sacre
+3  A: 

I think responding is nice, if you watch something like gmail you'll notice a lot of POSTs that get

ok

as the response, I like this. It is simple and concise.

The other thing to think about is how will you deal with the case where your request fails in some way, I think your client should probably report something to the user if it is unsuccessful, and therefore it'll need a response from the servlet.

thatismatt
+4  A: 

If you just want to provide a "success" status just return HTTP code 200. You don't have to return any stream since you just want to say "OK".

public void doGet(...) {
    response.setStatus(HttpServletResponse.SC_OK); 
}
adrian.tarau