java - 使用ajax请求发送时json值返回null

标签 java jquery ajax json

我正在尝试将 json 字符串发送到服务器,然后将其存储在数据库中

以下是我的代码:

$.ajax({
        url: 'JsonProcessor.do',
        type: 'post',
        dataType: 'json',
        data: {
                loadProds: 1,
                test: JSON.stringify(StateObject)
              },
        success: function (data) 
        {
        console.log("worked");
        },
         error: function (data) {
         alert('failed');
        }
        });

Servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String json = request.getParameter("test");
        System.out.println("json is: " + json);
        Connection con = null;
        ResultSet rs = null;
        try {
            con = OracleDBConnection.getConnection();
            String query = "insert into JJS (JSON_INFO) values(?)";
            PreparedStatement pst = con.prepareStatement(query);
            pst.setString(1, json);
            rs = pst.executeQuery();
            if (rs.next()) {
                System.out.println("sucess");
            } else {
                System.out.println("failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("DB releated exception");
        } 

但是,当我尝试打印 request.getparameter(json) 时,它返回 null。

这是我要发送的 json:

 {
    "cells": [
        {
            "type": "basic.Rect",
            "position": {
                "x": -2,
                "y": 33
            },
            "size": {
                "width": 71,
                "height": 625
            },
            "angle": 0,
            "isInteractive": false,
            "id": "e276b993-af5e-4e32-9879-fc3d817c0811",
            "z": 1,
            "attrs": {
                "rect": {
                    "fill": "#EEEEEE",
                    "stroke": "#008B8B",
                    "stroke-width": 2
                },
                ".": {
                    "magnet": false
                }
            }
        },
        {
            "type": "basic.Rect",
            "position": {
                "x": 10,
                "y": 50
            },
            "size": {
                "width": 51,
                "height": 41
            },
            "angle": 0,
            "isInteractive": false,
            "id": "f8826904-678c-4857-ad46-f86e69d1db32",
            "z": 2,
            "attrs": {
                "rect": {
                    "fill": "#D6F2FC",
                    "stroke": "#7E7E7E"
                },
                ".": {
                    "magnet": false
                }
            }
        },
        {
            "type": "basic.Circle",
            "size": {
                "width": 53,
                "height": 53
            },
            "position": {
                "x": 8,
                "y": 130
            },
            "angle": 0,
            "isInteractive": false,
            "id": "e4ee7b74-3c06-4e1e-8ce7-8baf6743c27c",
            "z": 3,
            "attrs": {
                ".": {
                    "magnet": false
                },
                "circle1": {
                    "fill": "white",
                    "stroke-width": 2,
                    "stroke": "green"
                }
            }
        },
        {
            "type": "basic.Circle",
            "size": {
                "width": 53,
                "height": 53
            },
            "position": {
                "x": 8,
                "y": 225
            },
            "angle": 0,
            "isInteractive": false,
            "id": "04d4a40b-f99b-4c16-89a9-7d072e30c4ad",
            "z": 4,
            "attrs": {
                ".": {
                    "magnet": false
                },
                "circle2": {
                    "fill": "white",
                    "stroke": "green"
                }
            }
        },
        {
            "type": "basic.Circle",
            "size": {
                "width": 53,
                "height": 53
            },
            "position": {
                "x": 8,
                "y": 320
            },
            "angle": 0,
            "isInteractive": false,
            "id": "97a01219-b7e2-4a52-9248-eb41dc7443b4",
            "z": 5,
            "attrs": {
                ".": {
                    "magnet": false
                },
                "circle3": {
                    "fill": "white",
                    "stroke": "green"
                }
            }
        },
        {
            "type": "basic.Rect",
            "position": {
                "x": 10,
                "y": 420
            },
            "size": {
                "width": 51,
                "height": 41
            },
            "angle": 0,
            "isInteractive": false,
            "id": "ed74bfd7-c7e2-4f68-85c3-0f1865243d3e",
            "z": 6,
            "attrs": {
                ".": {
                    "magnet": false
                },
                "rectGroup0": {
                    "fill": "white",
                    "stroke": "#7E7E7E"
                }
            }
        },
        {
            "type": "basic.Rect",
            "position": {
                "x": 35,
                "y": 505
            },
            "size": {
                "width": 45,
                "height": 45
            },
            "angle": 0,
            "isInteractive": false,
            "id": "008c90ea-2598-4761-8775-fc3601c8935d",
            "z": 7,
            "attrs": {
                "rect": {
                    "fill": "#FFED6B",
                    "stroke": "#DBCB62",
                    "width": 1,
                    "height": 1,
                    "stroke-width": 1,
                    "transform": "rotate(45)"
                },
                ".": {
                    "magnet": false
                }
            }
        }
    ]
}

最佳答案

您的代码存在多个问题:

发送时,jquery 已经为您进行了字符串化,因此您自己调用它时,实际上是在发送的 json 中创建一个字符串属性(您可以通过使用浏览器查看发送的数据来轻松检查这一点)

 $.ajax({
    url: 'JsonProcessor.do',
    type: 'post',
    dataType: 'json',
    data: {
            loadProds: 1,
            test: JSON.stringify(StateObject)
          },
      ...

实际上会创建一个如下所示的 http 请求正文:

{
   loadProds: 1,
   test: "{\"state\": .... "
}

所以只需写:

 $.ajax({
    url: 'JsonProcessor.do',
    type: 'post',
    dataType: 'json',
    data: {
            loadProds: 1,
            test: StateObject
          },
      ...

你会在这方面做得很好。

对于服务器部分,您实际上是在寻找名为“test”的请求参数。但这不是发送的内容。相反,您会得到一个包含 json 的“主体”。使用 dataType:json 时根本没有标准请求参数。

所以在你的情况下是

 String json = IOUtils.toString(request.getInputStream());

也不是你在那里检索的 json 包含“loadProps: 1”... 然后,您可能希望将字符串转换为对象(使用 jackson ),以便您可以使用它。

关于java - 使用ajax请求发送时json值返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31784440/

相关文章:

javax.crypto.IllegalBlockSizeException : Input length not multiple of 8 bytes

jquery - 如何使垂直图像缩略图 slider 响应?

asp.net - 如何终止对 .net Web 服务的 javascript 异步调用?

Javascript拉动刷新保留LastID变量

java - 动态添加组件并调用repaint/validate/revalidate

java - Lotus Notes API 在文档集合合并中给出错误

Java线程停止没有异常

javascript - 在 jQuery 延迟后加载 jquery 插件文件

jquery - $.ajax 与 DELETE 丢失参数

javascript - React 中的 Axios AJAX 调用仅返回初始状态