I am trying create a simple login page, where the username and password is checked against the data stored in the database (using hibernate). When successfully authenticating the user, I want to store the ID or the user object in the session bean.
For some reason a nullpointerexception is thrown when the user object is assigned to the session bean. As far as I have seen, the session Bean (userHolder) is null and therefore I it doesn't allow the object to be stored.
The error occurs on my UserDAO.java file on the following line,
userHolder.setCurrentUser(user);
Appreciate if someone could point me on the right direction.
JRE System Library - Java SE 8 [1.8.0_40] WildFly 8.x JSF v2.2
Entire code can be seen below.
userHolder.java
package domain;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserHolder implements Serializable {
private static final long serialVersionUID = 1L;
private User currentUser;
public User getCurrentUser() {
return currentUser;
}
public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
}
}
UserDAO.java
package domain;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import org.hibernate.Query;
import org.hibernate.Session;
@ManagedBean
@RequestScoped
public class UserDAO {
@ManagedProperty("#{userHolder}")
private UserHolder userHolder;
@PostConstruct
public void Dummy() {
User user = userHolder.getCurrentUser();
}
public UserHolder getUserHolder() {
return userHolder;
}
public void setUserHolder(UserHolder userHolder) {
this.userHolder = userHolder;
}
Session session = HibernateUtil.getSessionFactory().openSession();
public void save(User user){
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
public Integer getId (){
String hql = "select max(user.id) from User user";
Query query = session.createQuery(hql);
@SuppressWarnings("unchecked")
List<Integer> results = query.list();
Integer userId = 1;
if (results.get(0) != null ) {
userId = results.get(0) + 1;
}
return userId;
}
public String authenticate (String username,String password){
String hql = "FROM User user WHERE user.username = '" + username+ "' AND user.password = '" + password+ "'";
Query query = session.createQuery(hql);
@SuppressWarnings("unchecked")
List<User> results = query.list();
java.util.Iterator<User> iter = results.iterator();
if(results.isEmpty()){
return "error";
}
else{
while (iter.hasNext()) {
User user = iter.next();
System.out.println("Person: \"" + user.getFirstName() + "\", " + user.getLastName());
userHolder.setCurrentUser(user);
System.out.println(userHolder);
}
return "success";
}
}
}
LoginRequest.java
package domain;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
@ManagedBean
@RequestScoped
public class LoginRequest {
private String username;
private String password;
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public String login() {
UserDAO userDao = new UserDAO();
String response = userDao.authenticate(username, password);
if (response.equals("success")){
System.out.println("success");
return "loggedIn";
}else{
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Login failed", null));
}
return null;
}
}
login.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Web Shop - The Three Bears</title>
</head>
<body>
<h:messages/>
<h3>User Login Form</h3>
<h:form>
<h:outputLabel value="Username:" />
<h:inputText value="#{loginRequest.username}" /> <br />
<h:outputLabel value="Password" />
<h:inputSecret value="#{loginRequest.password}" /> <br />
<h:commandButton value="Login" action="#{loginRequest.login}" />
</h:form>
</body>
</html>
Error console
10:38:16,634 INFO [org.hibernate.dialect.Dialect] (default task-3) HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
10:38:16,760 INFO [org.hibernate.engine.transaction.internal.TransactionFactoryInitiator] (default task-3) HHH000399: Using default transaction strategy (direct JDBC transactions)
10:38:16,764 INFO [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] (default task-3) HHH000397: Using ASTQueryTranslatorFactory
10:38:17,014 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (default task-3) HHH000228: Running hbm2ddl schema update
10:38:17,015 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (default task-3) HHH000102: Fetching database metadata
10:38:17,017 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (default task-3) HHH000396: Updating schema
10:38:17,038 INFO [org.hibernate.tool.hbm2ddl.TableMetadata] (default task-3) HHH000261: Table found: webshopstudent.User
10:38:17,038 INFO [org.hibernate.tool.hbm2ddl.TableMetadata] (default task-3) HHH000037: Columns: [id, username, lastname, firstname, password]
10:38:17,038 INFO [org.hibernate.tool.hbm2ddl.TableMetadata] (default task-3) HHH000108: Foreign keys: []
10:38:17,039 INFO [org.hibernate.tool.hbm2ddl.TableMetadata] (default task-3) HHH000126: Indexes: [primary]
10:38:17,039 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (default task-3) HHH000232: Schema update complete
10:38:17,197 INFO [stdout] (default task-3) Hibernate: select user0_.ID as ID1_0_, user0_.FIRSTNAME as FIRSTNAM2_0_, user0_.LASTNAME as LASTNAME3_0_, user0_.PASSWORD as PASSWORD4_0_, user0_.USERNAME as USERNAME5_0_ from User user0_ where user0_.USERNAME='avizzzy' and user0_.PASSWORD='avizzzy'
10:38:17,236 INFO [stdout] (default task-3) Person: "Vinod", Sudharshan
10:38:17,236 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (default task-3) #{loginRequest.login}: java.lang.NullPointerException: javax.faces.FacesException: #{loginRequest.login}: java.lang.NullPointerException
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118) [jsf-impl-2.2.8-jbossorg-1.jar:]
at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [jsf-impl-2.2.8-jbossorg-1.jar:]
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.2.8-jbossorg-1.jar:]
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) [jsf-impl-2.2.8-jbossorg-1.jar:]
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:63) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:261) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:247) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:76) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:166) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:197) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:759) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_75]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_75]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_75]
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.2.8-jbossorg-1.jar:]
... 33 more
Caused by: java.lang.NullPointerException
at domain.UserDAO.authenticate(UserDAO.java:66) [classes:]
at domain.LoginRequest.login(LoginRequest.java:32) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_75]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_75]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_75]
at java.lang.reflect.Method.invoke(Method.java:606) [rt.jar:1.7.0_75]
at com.sun.el.parser.AstValue.invoke(AstValue.java:292) [javax.el-3.0.1-b05.jar:]
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304) [javax.el-3.0.1-b05.jar:]
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [jsf-impl-2.2.8-jbossorg-1.jar:]
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
... 34 more
10:38:17,243 ERROR [io.undertow.request] (default task-3) UT005023: Exception handling request to /WebShopStudentVersion/login.xhtml: javax.servlet.ServletException: java.lang.NullPointerException
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:63) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:261) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:247) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:76) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:166) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:197) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:759) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_75]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_75]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_75]
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.2.8-jbossorg-1.jar:]
at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [jsf-impl-2.2.8-jbossorg-1.jar:]
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.2.8-jbossorg-1.jar:]
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) [jsf-impl-2.2.8-jbossorg-1.jar:]
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
... 26 more
Caused by: java.lang.NullPointerException
at domain.UserDAO.authenticate(UserDAO.java:66) [classes:]
at domain.LoginRequest.login(LoginRequest.java:32) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_75]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_75]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_75]
at java.lang.reflect.Method.invoke(Method.java:606) [rt.jar:1.7.0_75]
at com.sun.el.parser.AstValue.invoke(AstValue.java:292) [javax.el-3.0.1-b05.jar:]
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304) [javax.el-3.0.1-b05.jar:]
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [jsf-impl-2.2.8-jbossorg-1.jar:]
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
... 34 more
I think there might be an issue with the annotations you are using. Assuming that you are using CDI you should change the annotations that you are using:
Try:
javax.enterprise.context.SessionScoped
instead of javax.faces.bean.SessionScoped;
javax.inject.Named
instead of javax.faces.bean.ManagedBean
javax.enterprise.context.RequestScoped
instead of javax.faces.bean.RequestScoped
javax.inject.Inject
instead of javax.faces.bean.ManagedProperty
This setup works for me with JEE7/Glassfish, so if this does not work you can narrow the problem further