首次登录Null指针异常(单例模式)

时间:2018-02-20 09:02:40

标签: java singleton

我有问题。请看一下这些代码。当我第一次点击登录按钮时它会抛出空指针异常,即使我输入正确的用户名和密码。但第二次一切都很好。我该如何解决这个问题? 我已经附加了OracleDBConnection和Login servlet。 OracleDBConnection文件中发生空指针异常。 谢谢你的阅读。

OracleDBConnection.java

    public class OracleDBConnection {

    private static volatile OracleDataSource instance = null;
    private static final DBPropertyController DB_PROPERTY = new DBPropertyController();
    private static final String URL = DB_PROPERTY.getProperty("url");
    private static final String USERNAME = DB_PROPERTY.getProperty("username");
    private static final String PASSWORD = DB_PROPERTY.getProperty("password");
    private static final String PORT = DB_PROPERTY.getProperty("port");

    private OracleDBConnection(){  
    }

    private static void initialize() {
        try {
            instance = new OracleDataSource();
            instance.setURL(URL);
            instance.setUser(USERNAME);
            instance.setPassword(PASSWORD);
            instance.setPortNumber(Integer.parseInt(PORT));
        } catch (SQLException ex) {
            Logger.getLogger(OracleDBConnection.class.getName()).log(Level.ERROR, ex);
        }
    }

    public static OracleDataSource getInstance() {
        OracleDataSource ods = OracleDBConnection.instance;

        if(ods == null) {
            synchronized(OracleDataSource.class){
                ods = OracleDBConnection.instance;
                if(ods == null) {
                    initialize();
                }
            }
        }
        return ods;
     }
   }

Login.java

    @WebServlet(name = "Login", urlPatterns = {"/login"})
    public class Login extends HttpServlet {

    private final LogController logger = new LogController();
    private final JWTController jwt_controller = new JWTController();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        LoginController login_controller = new LoginController();
        HttpSession session = request.getSession(true);

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        int role = 0;
        try {
            role = Integer.parseInt(request.getParameter("userrole"));
        } catch(NumberFormatException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.ERROR, null, ex);
            role=0;
        }

        if(username!=null && password!=null && !username.equals("") && !password.equals("") && isRoleValid(role)){
            if(login_controller.validateLogin(username, password, role)) {
                // get manager object
                Manager manager = login_controller.getManager(username, password, role);
                long currentEpochTime = LocalDateTime.now().atZone(ZoneId.systemDefault()).toEpochSecond();
                // set manager object to session
                session.setAttribute("manager", manager);
                //generate token
                String token = jwt_controller.generateToken(username, MD5.generate(password), role);
                // set token to cookie
                Cookie cookie = new Cookie("token", token);
                // add cookie to response
                response.addCookie(cookie);
                // check password expire date
                if(manager.getPaswd_edate() > currentEpochTime) {
                    // signed in
                    response.getWriter().write("Signed in");
                } else {
                    // expired
                    response.getWriter().write("Expired");
                }
                // add log
                logger.addLog(username, "Signed in.", request.getRemoteHost(), request.getHeader("user-agent"));
            } else {
                response.getWriter().write("Error");
            }
        } else {
                response.getWriter().write("Error");
        }
    }

    private boolean isRoleValid(int role) {
        return role==0 || role==1 || role==2 || role==3;
    }

}

1 个答案:

答案 0 :(得分:0)

你还没有提到你的NPE在哪里,但我想这是因为你的OracleDBConnection.getInstance()第一次调用它时会返回null个对象。

更改行

synchronized(OracleDataSource.class){
        ods = OracleDBConnection.instance;
        if(ods == null) {
            initialize();
        }
    }

synchronized(OracleDataSource.class){
        if(ods == null) {
            initialize();
        }
        ods = OracleDBConnection.instance;
    }