我有一个简单的(webprofile)EJB 3.1 应用程序并尝试确定@ApplicationScoped
CDI Bean 中的当前用户,所以我使用:
Principal callerPrincipal = this.sessionContext.getCallerPrincipal()
效果很好(所以我可以确定当前用户的名称)。
但是在任何(其他)EJB 中出现任何异常之后,此调用不再起作用(我需要重新启动服务器)!该方法不是返回调用者主体,而是抛出此异常。
Caused by: java.lang.NullPointerException
at com.sun.ejb.containers.EJBContextImpl.getCallerPrincipal(EJBContextImpl.java:421)
at de.mytest.service.CurrentUserService.getCurrentUserId(CurrentUserService.java:102)
有人可以给我提示我做错了什么吗?
实施细节:
服务器 Glassfish 3.1.2
当前用户服务:
@ApplicationScoped
public class CurrentUserService {
@Resource
private SessionContext sessionContext;
public long getCurrentUserId() {
if (this.sessionContext == null) {
throw new RuntimeException("initialization error, sessionContext must not be null!");
}
/*line 102 */ Principal callerPrincipal = this.sessionContext.getCallerPrincipal();
if (callerPrincipal == null) {
throw new RuntimeException("callerPrincipal must not be null, but it is");
}
String name = callerPrincipal.getName();
if (name == null) {
throw new RuntimeException("could not determine the current user id, because no prinicial in session context");
}
return this.getUserIdForLogin(name);
}
在 Faces Controller 和 CDI 服务之间抵抗的 EJB Facad
@Stateless
@RolesAllowed("myUser")
public class TeilnehmerServiceEjb {
@Inject
private CurrentUserService currentUserService;
public long currentUserId() {
return = currentUserService.getCurrentUserId();
}
}
web.xml
<security-constraint>
<web-resource-collection>
<web-resource-name>All Pages</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>myUser</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>mySecurityRealm</realm-name>
</login-config>
glassfish-web.xml
<security-role-mapping>
<role-name>myUser</role-name>
<group-name>APP.MY.USER</group-name>
</security-role-mapping>