我想写一个简单的在线BMI计算器,我在使用Ajax与servlet的初学者。我试图JSON对象发送到servlet,对象看起来像(这只是一个例子)
{ “FNAME”: “名字”, “L-NAME”: “姓”, “电子邮件”: “JH”}
该servlet应该采取的体重和身高,计算BMI在该网页的响应返回它
index.jsp页面上应用此代码后,
然后我处理在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");
}
}
}
我得到这个servlet这样的结果:
jsonObject
{"Request-URI":"","Method":"{\"fname\":\"name\",\"lname\":\"lastname\",\"email\":\"jh\"}","HTTP-Version":""}
jb
{"fname":"kjh","lname":"jkh","email":"jh"}
我怎样才能读取这个Servlet来计算BMI JSON数据?
我怎么能发送的结果(数字)来对网页的响应?
**我试图用ObjectMapper类,我得到的错误,我想补充的依赖,但日食停止工作,当我尝试更新索引
您可以通过使用String
的JSONObject
转换为JSONObject(String)
。像这样:
jsonObject = new JSONObject(jb.toString());
要创建一个新的JSON对象使用JSONObject()
和各种put(String, ?)
方法。例如:
JSONObject obj = new JSONObject();
obj.put("BMI", 100);
要发送一个响应,这样的事情应该工作:
response.setStatus(200);
response.setContentType("application/json");
PrintWriter writer = response.getWriter();
writer.append(obj.toString());
writer.close();