In this article, I'll address a simple solution of how I generalized and optimized my JSP codes for fetching current logged in user by creating a Java Bean/Class and import on my global.jsp file.

Steps

  1. Create a Java class: AuthenticatedUser.java with a package name com.myproject.util in my library (see sample codes in Code 1 below).
  2. Import my Java Class in my CQ global.jsp: <%@page import="com.myproject.util.AuthenticatedUser"%> and declare a local variable for my JSP/CQ component(s): AuthenticatedUser authedUser = new AuthenticatedUser(resourceResolver);.
  3. In my component, I include the gobal.jsp (i.e. <%@include file="/apps/myproject/components/global.jsp"%>). I can simply invoke the methods that I created in my AuthenticatedUser, for instance, authedUser.isAuthed() to check if the user is a guest or a logged in user.

Code 1

package com.mypackage.util;

/**
 *
 * @author Sothea Nim
 */

import com.day.cq.security.User;
import com.day.cq.security.Group;
import java.util.Iterator;
import java.util.ArrayList;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.commons.lang.StringUtils;

public class AuthenticatedUser
{
    private User currentUser;
    private Iterator<Group> currentUserGroups;
    private String groupsStr = "";
    
    /**
     *
     * @param resourceResolver
     */
    public AuthenticatedUser(ResourceResolver resourceResolver)
    {
        currentUser = resourceResolver.adaptTo(User.class);
        currentUserGroups = currentUser.memberOf();
        setGroupsStr();
    }
    
    /**
     *
     * @return currentUser
     */
    public User getCurrentUser()
    {
        return currentUser;
    }
    
    /**
     *
     * @return currentUserGroups
     */
    public Iterator<Group> getCurrentUserGroups()
    {
        return currentUserGroups;
    }
    
    public void setGroupsStr()
    {
        ArrayList arr = new ArrayList();
        
        if (currentUserGroups != null)
        {
            while(currentUserGroups.hasNext())
            {
                arr.add(currentUserGroups.next().getID());
            }
        }
        
        groupsStr = StringUtils.join(arr, "|");
    }
    
    public String getGroupsString()
    {
        return groupsStr;
    }
    
    public String getUserName()
    {
        return currentUser != null ? currentUser.getName() : "";
    }
    
    public boolean isAuthed()
    {
        return currentUser != null && !currentUser.getID().equals("anonymous") > 0 ? true : false;
    }
}

Enjoy!