Struts 2 Hibernate null pointer exception while submitting the form

前端 未结 2 947
太阳男子
太阳男子 2021-01-14 21:34

I am trying to create a registration page by integrating Struts 2 & Hibernate. But when I am running the below code , I am getting a null pointer exception when I click

2条回答
  •  不知归路
    2021-01-14 22:25

    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";
    }
    

提交回复
热议问题