简体   繁体   English

使用Ajax将JSON对象发送到servlet

[英]Sending JSON Object to servlet using Ajax

I am trying to write a simple online BMI calculator, I am a beginner in using Ajax with servlet. 我正在尝试编写一个简单的在线BMI计算器,我是将Ajax与servlet结合使用的初学者。 I am trying to send JSON object to the servlet, the object looks like (it is just an example) 我正在尝试将JSON对象发送到servlet,该对象看起来像(这只是一个示例)

{"fname":"name","lname":"lastname","email":"jh"} {“ fname”:“名称”,“ lname”:“姓氏”,“电子邮件”:“ jh”}

The servlet is supposed to take the weight and height and calculate BMI to return it in a response to the webpage 该Servlet应该考虑重量和高度并计算BMI以将其返回给网页

after applying this code on index.jsp page 在index.jsp页面上应用此代码后

then I handle the request in the servlet this way: 然后我以这种方式处理servlet中的请求:




$(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: 我在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? 如何在Servlet上读取JSON数据以计算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 **我尝试使用ObjectMapper类,但出现错误,尝试添加依赖项,但是当我尝试更新索引时,eclipse停止工作

You can convert the String to a JSONObject by using JSONObject(String) . 您可以使用JSONObject(String)String转换为JSONObject Like so: 像这样:

jsonObject =  new JSONObject(jb.toString());

To create a new JSON object use JSONObject() and the various put(String, ?) methods. 要创建新的JSON对象,请使用JSONObject()和各种put(String, ?) JSONObject() put(String, ?)方法。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM