如何查看谁从server.xml文件登录?

时间:2018-05-24 18:20:35

标签: java spring jsp spring-mvc authentication

我在Java Spring应用程序中配置了server.xml文件,以便在从数据库表和角色登录时对用户进行身份验证。我想知道如何在Java代码中检查谁登录到应用程序?

我知道在jsp文件中我可以使用以下语法来显示名称:

${pageContext.request.userPrincipal.name} .

3 个答案:

答案 0 :(得分:0)

http://www.baeldung.com/spring-security-track-logged-in-users

给出了非常漂亮的文章

只要将用户信息添加到会话中,或者根据用户登录系统或从系统注销,就可以利用HttpSessionBindingListener更新登录用户列表。

它将侦听HttpSessionBindingEvent类型的事件,无论何时设置或删除值,或者换句话说,绑定或未绑定到HTTP会话,都会触发这些事件。

@Component
public class LoggedUser implements HttpSessionBindingListener {

    private String username; 
    private ActiveUserStore activeUserStore;

    public LoggedUser(String username, ActiveUserStore activeUserStore) {
        this.username = username;
        this.activeUserStore = activeUserStore;
    }

    public LoggedUser() {}

    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        List<String> users = activeUserStore.getUsers();
        LoggedUser user = (LoggedUser) event.getValue();
        if (!users.contains(user.getUsername())) {
            users.add(user.getUsername());
        }
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        List<String> users = activeUserStore.getUsers();
        LoggedUser user = (LoggedUser) event.getValue();
        if (users.contains(user.getUsername())) {
            users.remove(user.getUsername());
        }
    }

    // standard getter and setter
}

您可以浏览整个code here

您还可以从Spring安全性中检索当前登录的用户 Go through this artical

或通过请求

request.getUserPrincipal().getName();

答案 1 :(得分:0)

在Spring MVC Controller中,只需添加以下语句:

String loggedUser = request.getUserPrincipal().getName();

其中requestHttpRequest类型的对象,Spring可根据需要提供给您。

答案 2 :(得分:0)

您可以编写一种方法来获取当前登录的用户,因为您可能需要以下各种位置:

public User getCurrentLoggedInUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            Object principal = auth.getPrincipal();
            if (principal instanceof User) {
                return ((User) principal);
            }
        }

    }
相关问题