Struts 2 Hibernate null pointer exception while submitting the form

梦想的初衷 提交于 2019-12-01 11:25:10

You misunderstand the DAO/DTO pattern. DAO/DTOs should not be static. And the sessionFactory better build normally only once per application, because it's time consuming procedure.

Better for you to implement a session per thread pattern. Write the class HibernateUtil to build the sessionFactory and get the session.

Then your DAO will look like

public class UserDao {

    public Session getSession() {
      return HibernateUtil.getSession();
    }

    public void closeSession() {
      HibernateUtil.closeSession();
    }

    public void addUser(User u) {    
        Session session = getSession();
        Transaction t = session.beginTransaction();
        int i = (Integer)session.save(u);
        t.commit();
        closeSession();
    }
}

in the action you write

private UserDao userDao = new UserDao();

public String execute() throws Exception {
    User u = new User();
    u.setAddress(address);
    u.setEmail(email);
    u.setName(name);
    u.setPhno(phno);
    u.setPwd(pwd);
    userDao.addUser(u);
    return "success";
}

In the class RegisterAction, you called the static method UserDao.addUser(u). The sf field of the UserDao class is only initialized when you call the constructor of UserDao, but in your case, the constructor is never called => the sf is never initialized thats why calling sf.openSession(); throws a NullPointerException();

You should initialize sf before calling one of its method.

Note that it is a very bad practice to initialize a static field in a no static and/or a no synchronized method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!