为什么我的FacesContext.getCurrentInstance()。getExternalContext()。getUserPrincipal()代码运行到NullPointer? [英] Why does my FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal() code runs to NullPointer?

查看:1458
本文介绍了为什么我的FacesContext.getCurrentInstance()。getExternalContext()。getUserPrincipal()代码运行到NullPointer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无状态的bean,它有一个方法,我想要获取当前/记录的用户。
我的代码获取它:

  Principal p1 = FacesContext.getCurrentInstance()。getExternalContext()。getUserPrincipal() ; 

但是我正在获得nullpointer异常。为什么会这样?



还有其他方式来获取登录的用户?
我正在使用weblogic。

解决方案

你不应该抓住 FacesContext 在EJB中。更重要的是,您的EJB应该完全免于任何JSF依赖关系。换句话说,您不应该从EJB中的 javax.faces。* 包导入任何代码。您的EJB应该被设计为可以在您可以想到的所有不同前端,如JSF,JAX-RS,Struts,Spring-MVC,甚至简单的香草Servlets中重用。



如果您使用容器管理的安全性或像Apache Shiro这样的安全框架,那么您应该使用API​​提供的设施。在plain vanillacontainer managed security(JAAS via web.xml 等等)的情况下,您应该从 SessionContext (这是正确的 javax.ejb package),可以注释为 @Resource

  @Resource 
private SessionContext context;

public void doSomething(){
Principal principal = context.getCallerPrincipal();
// ...
}

另一种选择是通过JPA实体表示的登录用户作为方法参数。


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.

这篇关于为什么我的FacesContext.getCurrentInstance()。getExternalContext()。getUserPrincipal()代码运行到NullPointer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆