gpt4 book ai didi

javascript - 如何在 doPost() 中的 servlet 内从 JavaScript 读取传入的 JSON?

转载 作者:行者123 更新时间:2023-11-30 07:56:56 25 4
gpt4 key购买 nike

我正在尝试通过 XMLHttpRequest (Ajax) 将一些 JSON 信息从 JavaScript 客户端发送到 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);

关于javascript - 如何在 doPost() 中的 servlet 内从 JavaScript 读取传入的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com