0

I try using the DAO design pattern on Servlets to store user input to MongoDB. Although found some useful hints on this post, and also this post. No doubt I got NullpointException. I wondered because I didn't create a collection and document to "insert" user input in my method on DaoImpl or something I don't understand how to work between Servlet and the DaoImpl class

Here is the UserDAO

public interface UserDao {
    List<User> getAllUsers();    
    void save(User user);    
    void updateUer(User user);    
    void deleteUser(User user);    
}

The DaoImpl, which I think is causing the NullPointException and want to fix it and doubt if here to connect to the database.

public class UserDaoImpl implements UserDao {

    @Override
    public void save(User user) {
        if (user == null) {
            System.out.println("not working!!!!!!!");
        } else {
            user.setName(user.getName());
            user.setEmail(user.getEmail());
            user.setPassword(user.getPassword());
        }
        // connection the db in here or in the Servlets controller?
    }

The Servlet Controller

public class RegisterServlet extends HttpServlet {
private UserDao userDao;
private User user;

public RegisterServlet(User user) {
this.user = user;
}

public RegisterServlet(UserDao userDao) {
this.userDao = userDao;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// Collect to database
MongoDatabase mdb = dBUtils.getMongoDB();    
assert mdb != null;

MongoCollection<Document> collection = mdb.getCollection("Users");

userDao.save(user);
}

Error Msg

Type Exception Report    
Description The server encountered an unexpected condition that prevented it from fulfilling the request.    
Exception    
java.lang.NullPointerException
    uts.asd.controller.RegisterServlet.doPost(RegisterServlet.java:54)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
Stu_Dent
  • 370
  • 1
  • 4
  • 19
  • 1
    Where is the `userDao` object created? Also, from the exception, can you tell on what line of the code you are getting the NPE. – prasad_ Sep 24 '20 at 12:27
  • I declared it on the Servlets. Should I put it in the Save method to do all the tasks? I'm afraid the error msg is all I got. – Stu_Dent Sep 24 '20 at 12:47
  • 1
    You forgot to tell which variable exactly is `null` and why exactly you expected it to be not `null`. As your question currently stands it's basically a duplicate of https://stackoverflow.com/q/218384 and you don't want that. In other words, fix your question to ask why exactly variable X null is (while clearly pointing out which variable exactly it is in your code snippet and how exactly it is created) instead of asking why exactly you get a NullPointerException. – BalusC Sep 24 '20 at 22:14
  • I will try to rectify my question later on today to find where is causing this exception, thanks. – Stu_Dent Sep 24 '20 at 23:40

1 Answers1

0

I investigated and follow this post advice, and finally can store data to MongoDB.

Here is what I did,

SaveUser method in UserDaoImpl class

    @Override
    public void save(User user) {

// this what I want to see. user is saved to db here
        try {
            MongoDatabase mdb = dBUtils.getMongoDB();
            assert mdb != null;

            if (user == null) {
                System.out.println("not working!!!!!!!");
            } else {

                users.add(new Document("Email", user.getEmail()).
                        append("Password", user.getPassword())
                        .append("Name", user.getName()));
                MongoCollection<Document> userlist = mdb.getCollection("Users"); //Create or get a collection "users" on mLab
                userlist.insertMany(users);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Servlet class

public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        User user = new User();
        UserDaoImpl userDao = new UserDaoImpl();

        user.setName(request.getParameter("name"));
        user.setEmail(request.getParameter("email"));
        user.setPassword(request.getParameter("password"));

        userDao.save(user);

        request.getRequestDispatcher("/welcome.jsp").forward(request, response);
    }
}
Stu_Dent
  • 370
  • 1
  • 4
  • 19