I am trying to write a simple online BMI calculator, I am a beginner in using Ajax with servlet. I am trying to send JSON object to the servlet, the object looks like (it is just an example)
{"fname":"name","lname":"lastname","email":"jh"}
The servlet is supposed to take the weight and height and calculate BMI to return it in a response to the webpage
after applying this code on index.jsp page
then I handle the request in the servlet this way:
$(document).ready(function(){
$("#simplepost").click(function(e)
{
var data = $('#ajaxform').serializeObject();
$.ajax({
type: "POST",
url: "AddServlet",
contentType: "application/json",
data: JSON.stringify(data),
success: function(response) {
// ...
}
});
});
});
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
public class AddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject jsonObject;
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { e.printStackTrace(); }
try {
jsonObject = HTTP.toJSONObject(jb.toString());
System.out.println("jsonObject "+jsonObject);
System.out.println("jb "+jb);
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
}
}
I get this result on the servlet:
jsonObject
{"Request-URI":"","Method":"{\"fname\":\"name\",\"lname\":\"lastname\",\"email\":\"jh\"}","HTTP-Version":""}
jb
{"fname":"kjh","lname":"jkh","email":"jh"}
How can I read JSON data on the Servlet to calculate the BMI?
And how could I send the result (a number ) as a response to the web page?
**I tried to use ObjectMapper class, I get errors, I tried to add dependencies but eclipse stops working when I try to update the indexes
You can convert the String
to a JSONObject
by using JSONObject(String)
. Like so:
jsonObject = new JSONObject(jb.toString());
To create a new JSON object use JSONObject()
and the various put(String, ?)
methods. For example:
JSONObject obj = new JSONObject();
obj.put("BMI", 100);
To send a response, something like this should work:
response.setStatus(200);
response.setContentType("application/json");
PrintWriter writer = response.getWriter();
writer.append(obj.toString());
writer.close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.