Reputation: 155
i am busy writing a very simple login page using JavaEE6, JSF 2.0 and CDI. My login page looks as follows (some stuff is removed for clarity):
<html>
<head>
<title>HomeBase - Login</title>
</head>
<body>
<h3>Login</h3>
<h:form>
<div>
<label>UserID:</label>
<h:inputText value="#{loginBean.userid}" />
</div>
<div>
<label>Password:</label>
<h:inputSecret value="#{loginBean.password}" />
</div>
<h:commandButton value="Login" action="#{loginBean.login}" />
</h:form>
</body>
</html>
and the backingbean looks as follows:
@ManagedBean
@RequestScoped
public class LoginBean implements Serializable {
@Inject Logger LOG;
private String userid;
private String password;
public String login() {
LOG.info("Start login procedure.");
if ("gast".equalsIgnoreCase(userid) && "gast".equals(password)) {
SessionBean sessionBean = (SessionBean) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("sessionBean");
User user = new User();
user.setUserid(userid);
user.setPassword(password);
user.setUsername("Gast");
sessionBean.setUser(user);
return "loginSuccess";
}
return "loginFailure";
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Now when i call the loginpage it gets correctly displayed. Both inputfields are empty. When in debugmode, i can see the getters for both fieldvalues are getting called. Next, i fill in the fields and press the submit button and an immediate nullpointer exception occurs. Clearly the LoginBean is instatiated the first time (when the page is displayed), but NOT when i press the commandbutton.
What happend?
Upvotes: 1
Views: 1352
Reputation: 1108722
The CDI @Inject
doesn't work in a JSF @ManagedBean
. Hence LOG
remains null
.
Use CDI @Named
instead of JSF @ManagedBean
and make sure that you import @RequestScoped
annotation from CDI javax.enterprise.context
package instead of JSF javax.faces.bean
.
Upvotes: 1