Friday, August 6, 2010

JSF Login Logout Example

Let's illustrate these ideas with a full example. We're going to implement user login/logout for an application that uses JSF. First, we'll define a Web Bean to hold the username and password entered during login:
@Named @RequestScoped
public class Credentials {
    private String username;
    private String password; 
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }   
    public String getPassword() { return password; }
    public void setPassword(String password) { this.password = password; }   
}
This Web Bean is bound to the login prompt in the following JSF form:

    
        Username:
        
        Password:
        
    
    
    

The actual work is done by a session scoped Web Bean that maintains information about the urrently logged-in user and exposes the User entity to other Web Beans:
@SessionScoped @Named
public class Login {
    @Current Credentials credentials;
    @PersistenceContext EntityManager userDatabase;
    private User user;
        public void login() {
        List results = userDatabase.createQuery(
           "select u from User u where u.username=:username and u.password=:password")
           .setParameter("username", credentials.getUsername())
           .setParameter("password", credentials.getPassword())
           .getResultList();
                if ( !results.isEmpty() ) {
          user = results.get(0);
         }
          }   
    public void logout() {
        user = null;
    }
     public boolean isLoggedIn() {
       return user!=null;
    }
        @Produces @LoggedIn User getCurrentUser() {
        return user;
    }
}
Of course, @LoggedIn is a binding annotation:
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD})
@BindingType
public @interface LoggedIn {}
Now, any other Web Bean can easily inject the current user:
public class DocumentEditor {
    @Current Document document;
    @LoggedIn User currentUser;
    @PersistenceContext EntityManager docDatabase;
      public void save() {
        document.setCreatedBy(currentUser);
        docDatabase.persist(document);
    }
   }
Hopefully, this example gives a flavor of the Web Bean programming model. In the next chapter, we'll explore Web Beans dependency injection in greater depth.

No comments:

Post a Comment