简体   繁体   中英

Login authentication - null pointer exception

I'm trying to validate user credentials using the following code, but I'm getting a null pointer exception every time the method is called:

public class LoginValidator {

    private static EntityManagerFactory emf;

    public static boolean validateUser(String email, String pswd){
        boolean status =  false;
        try{          
            EntityManager em;
            em =  emf.createEntityManager();
            Query q = em.createQuery("select c from Customer c where c.Email=:email and c.Password=:password")
                .setParameter("email", email)
                .setParameter("password", pswd);

            if (q.getResultList() != null)
                status = true;

            }catch(Exception e){System.out.println(e);}
            return status;
    }
}

Can anyone see why this is happening?

Also, is this a good way to perform authentication? I'm not so sure about my use of Query

您尚未实例化/注入EntityManagerFactory emf。

emf为null,您必须初始化它:

private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistanceUnitName");

If it is a Java EE application, as you indicate in the tags, use injection for the EntityManager :

@PersistenceContext
EntityManager em;

Do not use the EMF to instantiate the EM, it creates unnecessary overhead.

If it is more than a throw-away excercise, please consider hashing and salting the password, like this:

query.setParameter("password", computeSaltedHash(pswd));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM