4

我正在运行 Glassfish 3.0,并且正在实现 JDBCRealm 以进行登录身份验证。用户名和角色保存在名为 usertable 的表中。身份验证按预期工作。

但是现在的问题是当用户登录时,如何在应用程序中检索登录用户的用户名?

PS:我正在实现 JSF 页面和托管 Bean

4

3 回答 3

8

In JSF, you can retrieve the current Principal associated with the request and hence, the current session, using the ExternalContext object, which can be retrieved from the FacesContext. The Principal associated with the request is accessible from the ExternalContext using the getUserPrincipal() method:

FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();

The above invocation can be done in a JSF managed bean. You can invoke the getName() method on the Principal object to retrieve the name of the user as a String.

Note that, it possible for you to obtain a Principal instance that references the Anonymous user, if you are retrieving the Principal before authentication, or if the authentication scheme does not protect the entire site.

于 2011-07-12T22:02:35.977 回答
3

Request.getRemoteUserRequest.getUserPrincipal,独立于您用于身份验证的领域,因此如果您使用 File 领域进行测试,而使用 JDBC 领域进行生产,那么这两种情况都可以使用。顺便说一句,如果你使用 JDBCRealm 也可以看看FlexibleJDBCRealm

于 2011-07-12T21:56:32.153 回答
2

您的身份验证方法应返回包含名称的 java.security.Principal。

http://download.oracle.com/javase/1.4.2/docs/api/java/security/Principal.html

于 2011-07-12T21:57:06.753 回答