gpt4 book ai didi

java - 如何在服务器中接收表单参数值?

转载 作者:行者123 更新时间:2023-12-05 05:17:00 27 4
gpt4 key购买 nike

我有 React JS 应用程序,我使用 axios 库向服务器发送发布请求和表单提交。

客户要求:

sendData(data,price) {
axios.post('http://localhost:8080/SampleJavaAPP/UserServer', {
item: data,//these value
price:price//these value
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}

我不确定如何将这些值放入我在服务器中为获得这样的值所做的服务器

String name = request.getParameter("item");
String price = request.getParameter("price");

System.out.println("Result "+name + price);

但它在服务器中给出空值。如何在服务器中接收这些值参数?

最佳答案

由于 Axios 正在发送 Json 数据,您将无法直接读取它。有 2 种可能的解决方案:

  1. 将数据作为表单数据发送。

  2. 在 servlet 中读取和解析 JSON:

    public void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null) {
    jb.append(line);
    }
    } catch (Exception e) { /*report an error*/ }

    try {
    JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
    String price = jsonObject.get("price"); // will return price value.
    } catch (JSONException e) {
    throw new IOException("Error parsing JSON request string");
    }
    }

关于java - 如何在服务器中接收表单参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49673010/

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