how to set session attribute in cq5

6.4k views Asked by At

i am new to cq5, please help!! I am trying to set hashmap in session attribute. but for some reason i am getting JSP unable to compile. Please help!!

   <%@include file="/apps/test/test2/global.jsp"%>
         <%@page session="false"
          import="org.apache.sling.api.resource.ValueMap,
                  com.day.cq.wcm.api.WCMMode,
                  com.day.cq.dam.scene7.api.net.NetUtils,
                  org.apache.commons.lang.StringUtils,
                  javax.jcr.Session,
                  org.apache.jackrabbit.api.security.user.UserManager,
                  org.apache.jackrabbit.api.security.user.Authorizable"  %>

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


      <%
         Session session = resourceResolver.adaptTo(Session.class);
         Map<String, String> sessionValues = new HashMap<String, String>(); 

        for(int i=0;i<5;i++)
        {
          sessionValues.put("Id"+i, properties.get("test:Id"+i, "")); 
          sessionValues.put("Url"+i,properties.get("test:Url"+i,""));    
         }
       // put the hashmap as session    
         session.setAttribute("map", sessionValues);

         %>
2

There are 2 answers

4
Sharath Madappa On

The Session you have is a repository session , which is very different from a HTTP Session. Javax.jcr.Session is your gateway to the content repository. It is not used to store session related attributes and does not have any setAttribute method. It is used to read and write to repository ( http://jackrabbit.apache.org/jcr/how-jackrabbit-works.html ). If all your looking for is a http session , you should be getting it from slingRequest.

However if you use http sessions , you cannot cache pages in dispatcher ( https://forums.adobe.com/thread/960708 )

0
d33t On

As already answered, you are using the wrong session. Beside this, they are different use cases and it depends on what are you trying to achieve. If you are trying to share a property between different components during the request life time, you can set a servlet request attribute:

request.setAttribute(name, value)

This attribute will be reset when the request is finished. If you want to persist the data in the user session, than can use the http session object available from the request:

request.getSession().setAttribute(name, value)