Search code examples
javasessionliferayspring-portlet-mvc

Access PortletSession attributes (set by interceptor) from the controller (Spring Portlet MVC)


I'm new to Spring Portlet MVC, but I've been studying hard on it in the last few days. The context of my problem is the following

  1. I have a Spring Portlet MVC portlet with a single controller.
  2. The portlet is configured to call an HandlerInterceptor (method 'preHandleRender') anytime a user wants to access to a resource.
  3. The interceptor checks if the user is authenticated, if not, it retrieves the user's Liferay credentials to manage authentication on a number of other webservices (not interesting right now).
  4. After this, the interceptor stores the user data inside the PortletSession.

Now, how am I supposed to retrieve the user data stored in the PortletSession by the interceptor from inside the controller??

sessionInterceptor.preHandleRender

@Override
public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler) throws Exception {

    PortletSession session = request.getPortletSession(true);
              .
              .
              .
    session.setAttribute("userProfile", userProfileDomain,PortletSession.APPLICATION_SCOPE);
              .
              .
              .
    return true;
}

ViewController class

@Controller("viewController")
@RequestMapping(value = "view")
public class ViewController {

    //@Autowired
    private WebServiceTemplate webServiceTemplate = new WebServiceTemplate();

    @RenderMapping
    public String setModelAndView(RenderRequest request, ModelMap tgtModel) {
        logger.debug("<<  |  >> Starting.");

        PortletConfiguration conf = PortletConfiguration.getInstance();
              .
              .
    }
}

I am ready to give further information about my code if requested.


Solution

  • I was able to solve the problem and to identify my error.

    In the interceptor, as I showed in my question, I set the session attribute "userProfile" in the PortletSession.APPLICATION_SCOPE.

    session.setAttribute("userProfile", userProfileDomain,PortletSession.APPLICATION_SCOPE);
    

    As for the controller, I understood you have multiple options:

    • Pass the request (RenderRequest, in my case) as a parameter, the obtain the session (PortletSession, in my case) from the request and then retrieve the attribute from the session.
    • Pass directly the session as a parameter and then retrieve the attribute from it.

    However, whether you take the first or the second road, if you use the following instruction in the controller

    session.getAttribute("userProfile");
    

    you wont get anything because the attribute was set in PortletSession.APPLICATION_SCOPE.

    The correct instruction is:

    session.getAttribute("userProfile",PortletSession.APPLICATION_SCOPE);