I have a stateless bean which has a method, where I want to get the current/logged user.
My code to get it:
Principal p1 = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
But I am getting nullpointer exception on this. Why is that?
Or is there any other way to get the logged user?
I am using weblogic.
You're not supposed to grab the FacesContext
in an EJB. Even more, your EJBs should be completely free from any JSF dependencies. In other words, you should not have any code imported from javax.faces.*
package inside your EJBs. Your EJBs should be designed that way that they are reusable across all different front-ends you can think of such as JSF, JAX-RS, Struts, Spring-MVC and even "plain vanilla" Servlets.
If you're using container managed security or a security framework like Apache Shiro, then you're supposed to use the API-provided facilities for that. In case of "plain vanilla" container managed security (JAAS via web.xml
and so on), you're supposed to obtain it form SessionContext
(which is rightfully from javax.ejb
package) which can be injected as @Resource
.
@Resource
private SessionContext context;
public void doSomething() {
Principal principal = context.getCallerPrincipal();
// ...
}
An alternative would be to pass the JPA entity representation of the logged-in user as method argument.
verify the import of the following library:
javax.faces.bean.SessionScoped;
Try again