如何使用j_security_check获取已连接用户的数量及其角色? [英] How to get number of connected users and their role using j_security_check?

查看:137
本文介绍了如何使用j_security_check获取已连接用户的数量及其角色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过托管bean通过这种方式(使用j_security_check)获得了连接用户的用户名:

I get the username of the connected user (using j_security_check) this way, through a managed bean:

......
    username =   FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();

然后以这种方式在jsf页面中显示它:#{userBean.username} 但是我没有办法获得已连接用户的数量并获得他们的角色. 换句话说,我要显示用户名,用户角色和已连接用户数. 我怎样才能做到这一点! 预先感谢您的帮助!

And then display it in a jsf page this way : #{userBean.username} But I figured no way to get the number of connected users and get their role. In other words, I want to display besides the username, the user role and the number of connected users. How can I achieve this!? Thanks in advance for your help!

现在,我可以使用托管bean中的namedquery来获取连接用户的角色:

I can now get the Role of the connected user, using a namedquery in a managed bean :

public Users getUserRole(){
      try {
            Users auser = (Users)
            em.createNamedQuery("Users.findByUsername").
                    setParameter("username", getRemoteUser()).getSingleResult();
            return auser; 
        } catch (NoResultException nre) {
            JsfUtil.addErrorMessage(nre, "getUserRole Error");
            return null;
        }

    }

并在xhtml页面中:

and in the xhtml page:

<h:outputLabel for="rolefacet" value="Role: "/>
  <h:outputFormat id="rolefacet" value="#{UserBean.userRole.ugroup}" /> 

而ugroup是Users实体类中的角色名称.

while ugroup is the role name in the Users entity class.

一种对我仍然不起作用的解决方案是将HttpSessionListener添加到我的web.xml中:

One solution that still does not work for me is to add a HttpSessionListener to my web.xml:

package beans;

/**
 *
 * @author med81
 */

import java.io.Serializable;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.ArrayList;

import javax.faces.context.FacesContext;


public class SessionCounter implements Serializable, HttpSessionListener {

    private List sessions = new ArrayList();
   Object  s =  FacesContext.getCurrentInstance().getExternalContext().getSession(false);

    public Object getS() {
        return s;
    }

    public void setS(Object s) {
        this.s = s;
    }


    public SessionCounter() {
    }


    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        sessions.add(session.getId());

        session.setAttribute("counter", this);
    }


    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        sessions.remove(session.getId());

        session.setAttribute("counter", this);
    }

    /**
     * 
     * @return size of the session list
     */
    public int getActiveSessionNumber() {
        return sessions.size();
    }


}

推荐答案

这是一个基本的启动示例,当您使用Servlet 3.0时可以执行此操作,因此可以通过新的HttpServletRequest#login() API利用程序化登录.

Here's a basic kickoff example how you could do it when you're on Servlet 3.0 and thus are able to utilize programmatic login by the new HttpServletRequest#login() API.

登录表单:login.xhtml

<h:form>
    <h:inputText value="#{user.username}" />
    <h:inputSecret value="#{user.password}" />
    <h:commandButton value="Login" action="#{user.login}" />
    <h:messages />
</h:form>

用户管理器bean:com.example.UserManager

The user manager bean: com.example.UserManager

@ManagedBean(name="user")
@SessionScoped
public class UserManager implements Serializable {

    private String username;
    private String password;
    private User current;

    @EJB
    private UserService userService;

    @ManagedProperty("#{loginManager.logins}")
    private Set<User> logins;

    public String login() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

        try {
            request.login(username, password);
            current = userService.find(username, password);
        } catch (ServletException e) {
            // Unknown login. Will be handled later in current==null check.
        }

        if (current == null) {
            context.addMessage(null, new FacesMessage("Unknown login"));
            return null;
        } else {
            logins.add(current)
            return "home?faces-redirect=true";
        }
    }

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "login?faces-redirect=true";
    }

    // ...
}

注销(和会话无效)侦听器:com.example.LogoutListener

The logout (and session invalidate) listener: com.example.LogoutListener

@WebListener
public class LogoutListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        // NOOP.
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        UserManager userManager = (UserManager) event.getSession().getAttribute("user");
        if (userManager != null && userManager.getCurrent() != null) {
            userManager.getLogins().remove(userManager.getCurrent());
        }
    }

}

(请勿在logout()方法中执行此操作!这是会话无效触发的,会话无效将在调用logout()或会话过期时发生)

(Do not do this in logout() method! It's the session invalidation which triggers this, the session invalidation will take place when logout() is called OR when session has expired)

在任何登录视图中,您可以按以下方式获取当前用户和登录计数:

In any logged-in view you can obtain the current user and the login count as follows:

<p>Welcome, #{user.current.name}!</p>
<p>Total logged in users: #{user.logins.size()}</p>

这篇关于如何使用j_security_check获取已连接用户的数量及其角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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