java—如何通过servlet在aem中使用json创建节点?

aor9mmx1  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(386)

我用post方法创建了一个servlet。然后,我使用postman在body中使用json文件请求它。现在我想用从servlet检索到的json创建节点。我该怎么做?我知道如何创建node和setproperties,但只知道string。我想用这样的json文件创建node和setproperties

[
  {
    "_id": "5fc9dadaca52c28bb40011ee",
    "index": 0,
    "tags": [
      "laboris",
      "minim",
     ]
   },
   {
    "_id": "5fc9dada30930ef9d77c6d91",
    "index": 1,
    "tags": [
      "duis",
      "est",
     ]
   },
]

请帮帮我!

zxlwwiss

zxlwwiss1#

sling post servlet就是您要找的。导入操作具体包括:
https://sling.apache.org/documentation/bundles/manipulating-content-the-slingpostservlet-servlets-post.html#importing-内容结构-1
但是,对于对象,您需要json结构是值对。下面是一个基于示例json的示例:

{
    "node": "parent",
    "childs": {
        "child1": {
            "_id": "5fc9dadaca52c28bb40011ee",
            "index": 0,
            "tags": [
                "laboris",
                "minim"
            ]
        },
        "child2": {
            "_id": "5fc9dada30930ef9d77c6d91",
            "index": 1,
            "tags": [
                "duis",
                "est"
            ]
        }
    }
}

从前端

下面是一个用json文件调用sling post servlet的示例。您可以在js中遵循相同的模式,但是 :content 而不是 :contentFile ```
curl http://localhost:4502/content/newTree
-u admin:admin
-F":operation=import"
-F":contentType=json"
-F":replace=true"
-F":replaceProperties=true"
-F":contentFile=@my-json-file.json"


## 从后端

您还可以从后端创建post请求:

@Component(
service = Servlet.class,
property = {
ServletResolverConstants.SLING_SERVLET_METHODS + "=" + HttpConstants.METHOD_GET,
ServletResolverConstants.SLING_SERVLET_PATHS + "=" + "/bin/services/test"
})
public class Test extends SlingSafeMethodsServlet {

@Reference
private SlingRequestProcessor requestProcessor;

@Reference
private RequestResponseFactory requestResponseFactory;

@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    final Map<String, Object> parameters = ImmutableMap.of(
        ":operation", "import",
        ":contentType", "json",
        ":replaceProperties", "true",
        ":replace", "true",
        ":content", json
    );
    final HttpServletRequest postRequest = requestResponseFactory
        .createRequest(HttpConstants.METHOD_POST, "/content/newTree", parameters);
    final HttpServletResponse postResponse = requestResponseFactory.createResponse(output);

    try {
        requestProcessor.processRequest(postRequest, postResponse, request.getResourceResolver());
    } catch (ServletException e) {
        // handle exception
    }
}

}

相关问题