I am trying to get liferay userId (I am using primefaces 6.2 in Liferay 7).
What I have tried so far is:
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
ThemeDisplay td =(ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
long userId = td.getUserId();
I am getting the below error:
ERROR [stderr] (default task-49) java.lang.ClassCastException: com.liferay.faces.bridge.ext.filter.internal.ResourceRequestBridgeLiferayImpl cannot be cast to javax.servlet.http.HttpServletRequest
I have searched the problem, but not able to find out a working solution. Any help would be highly appreciated.
Thanks in advance.
I also tried using PortletRequest. Below is the code.
PortletRequest request = (PortletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
ThemeDisplay td =(ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
User user = td.getUser();
But now ThemeDisplacy class is not found
java.lang.NoClassDefFoundError: com/liferay/portal/theme/ThemeDisplay: javax.el.ELException: java.lang.NoClassDefFoundError: com/liferay/portal/theme/ThemeDisplay
I am not sure where i am missing.
Thanks
To fetch the Liferay User object, you could use the following snippet:
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
User u = PortalUtil.getUser(portletRequest);
Please also read this article about the return value of ExternalContext.getRequest() - this might be the reason of your cast error.
The article further explains that: "the ExternalContext.getRequest() method returns an Object
instead of an javax.servlet.http.HttpServletRequest
. When this method is used in a portal, the Object can be cast to a javax.portlet.PortletRequest."