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 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:
<f:form> <h:panelGrid columns="2" rendered="#{!login.loggedIn}"> <h:outputLabel for="username">Username:</h:outputLabel> <h:inputText id="username" value="#{credentials.username}"/> <h:outputLabel for="password">Password:</h:outputLabel> <h:inputText id="password" value="#{credentials.password}"/> </h:panelGrid> <h:commandButton value="Login" action="#{login.login}" rendered="#{!login.loggedIn}"/> <h:commandButton value="Logout" acion="#{login.logout}" rendered="#{login.loggedIn}"/> </f:form
The actual work is done by a session scoped Web Bean that maintains information about the currently 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<User> 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.