Hi Prince,
We'd like to suggest you to go through the below piece of code. It worked as expected for us and JCR session was created successfully.
MyServlet.java:
import java.io.IOException;
import javax.jcr.Session;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.techaspect.aemconcepts.core.services.MyUserService;
public class MyServlet extends SlingAllMethodsServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(MyServlet.class);
@Reference
MyUserService myUserService;
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
try {
Session sessionObj = myUserService.getRepoConnection();
response.getWriter().print("session object:::" + sessionObj);
} catch (Exception e) {
LOG.error("ERROR:::", e);
}
}
}
MyUserService.java:
import javax.jcr.Session;
public interface MyUserService {
public Session getRepoConnection();
}
MyUserServiceImpl.java:
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Session;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.techaspect.aemconcepts.core.services.MyUserService;
@Component(service = MyUserService.class)
public class MyUserServiceImpl implements MyUserService {
private static final Logger LOG = LoggerFactory.getLogger(MyUserServiceImpl.class);
@Reference
private ResourceResolverFactory resolverFactory;
public Session getRepoConnection() {
Session session = null;
ResourceResolver resourceResolver = null;
try {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put(ResourceResolverFactory.SUBSERVICE, "readService");
resourceResolver = resolverFactory.getServiceResourceResolver(paramMap);
session = resourceResolver.adaptTo(Session.class);
Node root = session.getRootNode();
LOG.info("Root node:::{}", root.getPath());
} catch (LoginException e) {
LOG.error("LoginException:::", e);
}
return session;
}
}
We hope this helps!
Regards,
TechAspect Solutions