0

I have a assignment in Sling Servlets. Here, In my application, I've to create a property within the node corresponding to logged in user and add a boolean value to this property. This has to be done dynamically when the user logs in for the first time. On subsequent login, this property has to be fetched for validation.

For getting the resource, I've written the following lines of code.

ResourceResolver resourceResolver = slingRequest.getResourceResolver(); Resource campaignResource = resourceResolver.getResource("/home/users/V/VSukz/profile"); ValueMap campaignProperties = campaignResource.adaptTo(ValueMap.class); String title = campaignProperties.get("category", "");

I'm not able to do so for Post. I need help in this part.

Suban Jacob
  • 11
  • 1
  • 4

2 Answers2

1

Here is the example, how to get a javax.jcr.Session object, how to find a Node object and how to add a property to the node.

public class ExampleServlet extends SlingAllMethodsServlet {

    @Reference(policy=ReferencePolicy.DYNAMIC, cardinality=ReferenceCardinality.MANDATORY_UNARY)
    protected SlingRepository repository;

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        Session session= null;
        String path = "/path/to/your/node";
        try {
            session = repository.loginService(null, null); // this method requires additional setting in Apache Sling Service User Mapper Service. (AEM6)
            //session = repository.loginAdministrative(repository.getDefaultWorkspace()); //this method is deprecated (it was used in previous versions)
            Node node = session.getNode(path);
            node.setProperty("propertyName", "propertyValue");
            session.save();
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            e.printStackTrace();
        } finally {
            if(session != null) session.logout();
        }

    }

    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException{
        doGet(request,response);
    }
}
kmb
  • 871
  • 5
  • 17
  • 34
  • Here's a pretty good resource for doing service mapping, http://www.wemblog.com/2014/08/how-to-use-sessions-and-resource.html – Cris Rockwell Feb 20 '15 at 23:32
  • @ChristopherRockwell true, I just passed two null and null as the parameters to simplify my answer. Thanks for your link. – kmb Feb 21 '15 at 00:42
0

Please refer to How to set a resource property

With the new versions of Sling, ModifiableValueMap can come in handy to set values in a JCR Node.

Community
  • 1
  • 1
user1057653
  • 176
  • 1
  • 8