Reputation: 1
I have created a servlet with method post. Then, i used postman to request it with the JSON file in body. Now i want to create node with JSON that i retrieved from servlet. How can i do that? I know how to create node and setProperties but only String. I want to create node and setProperties with the JSON file like that
[
{
"_id": "5fc9dadaca52c28bb40011ee",
"index": 0,
"tags": [
"laboris",
"minim",
]
},
{
"_id": "5fc9dada30930ef9d77c6d91",
"index": 1,
"tags": [
"duis",
"est",
]
},
]
Please help me!
Upvotes: 0
Views: 1702
Reputation: 11
The Sling Post Servlet is what you're looking for. The import operation specifically:
However, you need your JSON structure to be value pairs in the case of objects. Here's an example based on your sample json:
{
"node": "parent",
"childs": {
"child1": {
"_id": "5fc9dadaca52c28bb40011ee",
"index": 0,
"tags": [
"laboris",
"minim"
]
},
"child2": {
"_id": "5fc9dada30930ef9d77c6d91",
"index": 1,
"tags": [
"duis",
"est"
]
}
}
}
Here's an example calling the sling post servlet with a json file. You can follow the same pattern in JS but specifying :content
instead of :contentFile
curl http://localhost:4502/content/newTree \
-u admin:admin \
-F":operation=import" \
-F":contentType=json" \
-F":replace=true" \
-F":replaceProperties=true" \
-F":[email protected]"
You can also create a POST request from the back end:
@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
}
}
}
Upvotes: 0