14

I'm working with : Liferay 6.0.6 with JBoss 5.1 and Struts2.

My question is, how to get the current user in Liferay once logged in, using a Java code.

Felix Christy
  • 2,179
  • 1
  • 19
  • 32
Sabrina
  • 143
  • 1
  • 1
  • 5
  • I meant, the solution should be a Java Code and we have to retrieve the current user by E-mail :) – Sabrina May 04 '12 at 12:16

3 Answers3

28

In your doView/processAction method do following

User user = (User) request.getAttribute(WebKeys.USER);

or use the ThemeDisplay object. It contains another information like companyId, groupId, ...

ThemeDisplay td  =(ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
User user = td.getUser();

Classes ThemeDisplay, User nad WebKeys are part of portal-service.jar.

If you need just some id to identify current user you can also use

String userId = request.getRemoteUser();

This solution is not Liferay specific and should be portable among jsr-286 portals.

František Hartman
  • 14,436
  • 2
  • 40
  • 60
  • 1
    can you tell me more about the instance "request". how to initialize it ? – Sabrina May 04 '12 at 12:55
  • 2
    Its either RenderRequest, ActionRequest, EventRequest or ResourceRequest. If you are not familiar with them then you should read some portlet tutorial, e.g http://www.liferay.com/documentation/liferay-portal/6.0/development/-/ai/understanding-the-two-phases-of-portlet-execution – František Hartman May 04 '12 at 19:28
  • User currentUser = LiferayFacesContext.getInstance().getUser(); – Aalkhodiry Oct 28 '13 at 15:22
6

Liferay provides Util class

com.liferay.portal.util.PortalUtil

This class contains all utility methods to get the frequently used attributes.

Try using PortalUtil.getUser(PortletRequest portletRequest) method to avoid creating new objects and references.

Felix Christy
  • 2,179
  • 1
  • 19
  • 32
  • What's is the different with ThemeDisplay? – TuGordoBello May 26 '15 at 14:07
  • @zhelon, nothing, you fetch themeDisplay from request, and then getUser() from it, PortalUtil.getUser() fetches the same from request, if you see PortalImpl.getUser() then you will notice this request.getAttribute(WebKeys.USER); – Felix Christy May 27 '15 at 07:44
6

This is an other possible way to do it :

private LiferayFacesContext liferayFacesContext = LiferayFacesContext.getInstance();
User currentUser=liferayFacesContext.getUser()
Charaf JRA
  • 8,249
  • 1
  • 34
  • 44