2

What happens when you login?

The login page is defined using pure XHTML with JSF controls. The form uses JSF EL value binding and method binding expressions to refer to Seam components. For example, #{user.username} refers to a property of the User entity bean and #{login.login} refers to a method of the LoginAction stateless session bean. Both beans are EJB 3.0 POJOs managed by Seam.

<div> <h:outputLabel for="username">Login Name</h:outputLabel> <h:inputText id="username" value="#{user.username}" /> </div> <div> <h:outputLabel for="password">Password</h:outputLabel> <h:inputSecret id="password" value="#{user.password}" /> </div> ... ... <div class="buttonBox"> <h:commandButton action="#{login.login}" value="Account Login" class="button" /> </div>

The User enity bean is mapped to the Seam context variable named user bean via the @Name annotation. User is a session scoped bean, meaning that the user component value is retained for the entire session for each user. You might also notice there are validation annotation on the data properties. We will discuss those annotations in the next step.

@Entity @Name("user") @Scope(SESSION) public class User implements Serializable { private String username; private String password; private String name; @NotNull @Length(min=5, max=15) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Id @Length(min=5, max=15) public String getUsername () { return username; } public void setUsername (String username) { this.username = username; } // ... ... }

LoginAction is an EJB 3.0 session bean mapped to the Seam context variable named login. When the login button is clicked, the JSF method binding #{login.login} is evaluated, and the login() method is invoked upon LoginAction.

@Stateless @Name("login") public class LoginAction implements Login { @In @Out private User user; @PersistenceContext private EntityManager em; public String login() { List<User> results = em.createQuery("from User where username=:username and password=:password") .setParameter("username", user.getUsername()) .setParameter("password", user.getPassword()) .getResultList(); if ( results.size()==0 ) { FacesMessages.instance().add("Invalid login"); return "login"; } else { user = results.get(0); Contexts.getSessionContext().set("loggedIn", true); return "main"; } } }

The @In annotation tells Seam to inject a User when any method of LoginAction is invoked. The @Out annotation indicates the LoginAction bean can change the value of the user context variable and make the new instance available to other session beans and JSF pages.