我必须使用 Spark(Java 框架)读取客户端发送的一些数据。

这是客户端发布请求的代码。我正在使用 jQuery。

$.post("/insertElement",
{item:item.value, value: value.value, dimension: dimension.value });

服务器代码:
post(new Route("/insertElement") {
        @Override
        public Object handle(Request request, Response response) {
            String item = (String) request.attribute("item");
            String value = (String) request.attribute("value");
            String dimension = (String) request.attribute("dimension");
            Element e = new Element(item, value, dimension);
            ElementDAO edao = new ElementDAO();
            edao.insert(e);
            JSONObject json = JSONObject.fromObject( e );
            return json;
        }
    });

我正在使用 Spark,所以我只需要定义路线。
我想将客户端发送的数据存储在数据库中,但所有属性都为空。

我认为这种方式是不正确的。如何读取发送的数据?

最佳答案

他们使用 HTTP POST 发送数据的方式,您将 JSON 作为请求 主体 发布,而不是作为请求 属性 发布。这意味着您不应该使用 request.attribute("item") 和其他,而是将请求正文解析为 Java 对象。您可以使用该对象创建 element 并使用 DAO 存储它。

10-05 20:38
查看更多