JSF Listing Active Users

Created: 15.10.2013

Listing all active users can be a useful feature for Web 2.0 applications. To realize such a feature, you need an ApplicationScoped ManagedBean that tracks all user logins.

public class ActiveUserHandler {
	private List activeUsers = new ArrayList<>();
	public void addUser(User user){
    public void removeUser(User user){
	public List getActiveUsers(){
		return activeUsers;

Every time a user logs in or logs out, the ApplicationScoped Handler needs to be notified. You might use a SessionScoped LoginHandler like this:

public class LoginHandler implements HttpSessionListener{
	private EntityManager em;
	private UserTransaction utx;
    private ActiveUserHandler activeUserHandler;

	private String username = "";
	private String password = "";
	private User currentUser = null;
	public String login(){
		TypedQuery<User> query = em.createQuery("select u from User u where u.username=:username, User.class);
        query.setParameter("username", username);
			User result = query.getSingleResult();
			String hashedPassword = SecurityUtils.hashPasswordAndSalt(password + currentUser.getSalt());
				currentUser = result;
				return "/welcome.xhtml?faces-redirect=true";
			} else {
				return "/login.xhtml?faces-redirect=true";
		} catch (NoResultException e){
			return "/login.xhtml?faces-redirect=true";
	public String logout() {
		 return "/index.xhtml?faces-redirect=true";
    public void sessionCreated(HttpSessionEvent e){
    public void sessionDestroyed(HttpSessionEvent e){
        currentUser = null;