我如何在doPost()中的servlet中读取来自JavaScript的传入JSON

How do i read an incoming JSON from JavaScript inside a servlet in doPost()?

本文关键字:读取 JavaScript JSON servlet doPost 中的      更新时间:2023-09-26

我试图通过XMLHttpRequest (Ajax)从JavaScript客户端发送一些JSON信息到java中的servlet,但我不知道获取和解码数据的正确方法。我在网上看过很多例子,但似乎没有一个是有效的。我只是想知道我应该使用哪种方法,比如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();
        }
    }
}

为了在servlet中检索请求体,您需要调用ServletRequest#getReader。在您的示例中,它看起来像这样:

BufferedReader reader = request.getReader();

你可以把这个Reader传递给JSONTokener的构造函数:

JSONTokener tokener = new JSONTokener(reader);

最后您可以将其解析为JSONObject:

JSONObject jObj = new JSONObject(tokener);