I implemented a servlet that receives a JSON string, converts it into an object and inserts its data into the database. I call that servlet from a HTML page using AJAX and post the JSON string to it. In my case, does it make sense for the servlet to write anything to the response?
Asked
Active
Viewed 561 times
2
-
Return the word of success or failure for your work – rickz Sep 24 '15 at 14:49
3 Answers
2
Since you mention that you had an ajax call to your servlet, you should probably return a JSON status back to calling .ajax()
response.setContentType("application/json");
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter out = response.getWriter();
// Assuming your database operation insert is successful
JSONObject json = new JSONObject();
// put a success message into the JSON object .
json.put("status", "success");
out.print(jsonObject);
out.flush();
On the client side
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
}

vijayasundaram
- 41
- 1
- 3
1
You need not to return anything. Once the request cycle complete, your browser receives the response object of it as a stream. If you want to add something to it.
response.getWriter().write(somedata);
That somedata
you'll receive in your AJAX callback.
For detailed example with codes : How to use Servlets and Ajax?

Community
- 1
- 1

Suresh Atta
- 120,458
- 37
- 198
- 307
-
-
You need not return anything if you don't want anything on client side. If you want to acknowldgement return your data. For ex : `1` `0`,`true`,`false` etc even a List of objects in json format. – Suresh Atta Sep 24 '15 at 14:50
1
It is good practice to perform the database transaction inside a try catch block, and return a success / failure status flag to the client, in case the transaction failed for whatever reason.

aengus
- 605
- 6
- 13