Why does my FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal() code runs to NullPointer?

大憨熊 提交于 2019-12-11 03:33:39

问题


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.


回答1:


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.




回答2:


verify the import of the following library:

javax.faces.bean.SessionScoped;

Try again



来源:https://stackoverflow.com/questions/19772780/why-does-my-facescontext-getcurrentinstance-getexternalcontext-getuserprinci

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!