我正在尝试通过XMLHttpRequest(Ajax)从JavaScript客户端向Java中的servlet发送一些JSON信息,但我不知道获取和解码数据的正确方法。我在网上看过很多例子,但似乎没有人工作。我只是想知道我应该使用的方法如request.getParameter()以及我需要的JSONParser之类的对象。我试图使用的每个代码或示例都不起作用,在参数中返回null,或者抛出java.lang.NullPointerExceltion。 Post请求到达servlet,因为我监视响应,但我无法访问数据。我会发布我的代码。非常感谢能帮助我的人。
HTML(index.html):
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX JSON Example</title>
<script type="text/javascript" src="ajaxjsonfunctions.js"></script>
</head>
<body>
<input type="text" id="name" name="name" value="PuMa" placeholder="Name..."/>
<input type="text" id="age" name="age" value="28" placeholder="Age..."/>
<input type="text" id="country" name="country" value="Colombia" placeholder="Country..."/>
<input type="button" id="sendjsonpost" name="sendjsonpost" value="Send JSON POST" />
<hr/>
</body>
</html>
JavaScript,Ajax(ajaxjsonfunctions.js):
window.onload = function()
{
var sendjsonpost = document.getElementById("sendjsonpost");
xhr = new XMLHttpRequest();
sendjsonpost.onclick = function()
{
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
var country = document.getElementById("country").value;
if (name == "" || age == "" || country == "")
alert("Debe ingresar todos los datos.");
else
enviarDatosPost(name, age, country);
}
function enviarDatosPost(name, age, country)
{
xhr.onreadystatechange = prepararRespuestaPost;
xhr.open("POST", "MessagesJSON", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var datosJSON = crearDatosJSON(name, age, country);
alert(JSON.stringify(datosJSON));
xhr.send(JSON.stringify(datosJSON));
}
function crearDatosJSON(name, age, country)
{
var datosJSON = {name : name, age : age, country : country};
return datosJSON;
}
function prepararRespuestaPost()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
alert(xhr.responseText +" --- " + xhr.statusText);
}
}
}
}
Servlet(MessagesJSON.java):
package com.puma.servlets;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.*;
import org.json.JSONObject;
import org.json.simple.*;
@WebServlet(asyncSupported = true, urlPatterns = { "/MessagesJSON" })
public class MessagesJSON extends HttpServlet
{
private static final long serialVersionUID = 1L;
public MessagesJSON()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
JSONObject jObj = new JSONObject(request.getParameter("name"));
Iterator iterKey = jObj.keys(); //gets all the keys
while(iterKey.hasNext())
{
String jsonKey = iterKey.next().toString();
String jsonValue = jObj.getString(jsonKey);
System.out.println(jsonKey + " --> " + jsonValue );
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
为了在servlet中检索请求的主体,您需要调用ServletRequest#getReader
。在你的情况下,这将是这样的:
BufferedReader reader = request.getReader();
然后,您可以将此Reader传递给JSONTokener
:
JSONTokener tokener = new JSONTokener(reader);
最后,您可以将其解析为JSONObject
:
JSONObject jObj = new JSONObject(tokener);