JSF web application 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 request-scoped bean to hold the username and password entered during login,
with constraints defined using annotations from the Bean Validation specification:
This bean is bound to the login prompt in the following JSF form:
Username:
Password:
]]>
Users are represented by a JPA entity:
(Note that we're also going to need a persistence.xml file to configure the JPA persistence
unit containing User.)
The actual work is done by a session-scoped bean that maintains information about the currently logged-in user
and exposes the User entity to other beans:
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);
}
else {
// perhaps add code here to report a failed login
}
}
public void logout() {
user = null;
}
public boolean isLoggedIn() {
return user != null;
}
@Produces @LoggedIn User getCurrentUser() {
return user;
}
}]]>
@LoggedIn and @UserDatabase are custom qualifier annotations:
We need an adaptor bean to expose our typesafe EntityManager:
Now DocumentEditor, or any other bean, can easily inject the current user:
Or we can reference the current user in a JSF view:
signed in as #{currentUser.username}
]]>
Hopefully, this example gave you a taste of the CDI programming model. In the next chapter, we'll explore
dependency injection in greater depth.