Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Servlet JDBC身份验证_Java_Jsp_Servlets - Fatal编程技术网

Java Servlet JDBC身份验证

Java Servlet JDBC身份验证,java,jsp,servlets,Java,Jsp,Servlets,我有一个表单,它向Servlet提交POST请求。我创建了一个类DbConnection,它管理对MySQL数据库的身份验证,当我使用静态main方法测试它时,该数据库工作得非常好。当我在Servlet中使用这个类时,它总是给我这个错误 我的代码有什么问题 下面是DbConnection类 package com.cloud.db; public class DbConnection { private Connection conn; private String user

我有一个表单,它向Servlet提交POST请求。我创建了一个类DbConnection,它管理对MySQL数据库的身份验证,当我使用静态main方法测试它时,该数据库工作得非常好。当我在Servlet中使用这个类时,它总是给我这个错误

我的代码有什么问题

下面是DbConnection类

package com.cloud.db;

public class DbConnection {

    private Connection conn;
    private String user = NAME;
    private String passwd = SOME_PASSWORD;
    private Statement stmt;
    private ResultSet result;
    private PreparedStatement auth;

    public DbConnection() {
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudbase", user, passwd);
            stmt = conn.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean authenticate(String usrname, String pwd) throws SQLException {
        PreparedStatement stm = conn.prepareStatement("select * from users where email=? and password = ?");
        stm.setString(1, usrname);
        stm.setString(2, pwd);
        ResultSet result = stm.executeQuery();

        if (result.next()) {
            return true;
        } else {
            return false;
        }
    }
}
这是我的servlet

package com.cloud.db;

import com.cloud.*;
import java.sql.*;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/auth")
public class Auth extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Auth() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = request.getParameter("email");
        String passwd = request.getParameter("pwd");
        DbConnection connect = new DbConnection();

        try {
            new DbConnection().authenticate("example@cloudserver.com", "password");
        } catch (SQLException e) {
            System.out.println("Error :" + e.getMessage());
        }
    }
}

根据您发布的内容,我认为问题在于:

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudbase",user,passwd);
stmt = conn.createStatement();
DriverManager.getConnection正在返回null和,null.create。。。正在投掷NPE

如何验证:在conn=。。。然后查看连接是否为空 如何解决这个问题: 1确保驱动程序类位于类路径中并已加载。
2在使用对象之前,请确保它已初始化。

根据您发布的内容,我认为问题在于:

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudbase",user,passwd);
stmt = conn.createStatement();
DriverManager.getConnection正在返回null和,null.create。。。正在投掷NPE

如何验证:在conn=。。。然后查看连接是否为空 如何解决这个问题: 1确保驱动程序类位于类路径中并已加载。
2在使用对象之前,确保它已初始化。

在本地和tomcat中运行代码的最大区别是JDBC驱动程序的位置,因此最可能的问题是tomcat找不到JDBC驱动程序。Tomcat希望在$CATALINA_HOME/lib中找到一个驱动程序。下面是设置MySQL数据源的说明

目前,您的异常处理掩盖了正在发生的事情。最初的问题发生在DBConnection构造函数中,但由于捕获到异常,因此authenticate方法继续使用null连接运行,从而导致NullPointerException

Tomcat应该将DBConnection构造函数中生成的异常写入控制台,这样您就可以在那里查找原始问题。要修复异常处理,您可以将DbConnection代码更改为以下内容:

public boolean authenticate(String usrname,String pwd) throws SQLException {
    Connection conn = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/cloudbase",user,passwd);
    try {
        PreparedStatement stm = conn.prepareStatement(
        "select * from users where email=? and password = ?");
        stm.setString(1, usrname);
        stm.setString(2, pwd);
        ResultSet result = stm.executeQuery();
        return result.next();
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            // use a logger instead of stdout
            log.info("close caused exception", e); 
        }
    }
}

这确保抛出的异常是导致原始问题的异常。

本地运行代码和在tomcat中运行代码的最大区别是JDBC驱动程序的位置,因此最有可能的问题是tomcat找不到JDBC驱动程序。Tomcat希望在$CATALINA_HOME/lib中找到一个驱动程序。下面是设置MySQL数据源的说明

目前,您的异常处理掩盖了正在发生的事情。最初的问题发生在DBConnection构造函数中,但由于捕获到异常,因此authenticate方法继续使用null连接运行,从而导致NullPointerException

Tomcat应该将DBConnection构造函数中生成的异常写入控制台,这样您就可以在那里查找原始问题。要修复异常处理,您可以将DbConnection代码更改为以下内容:

public boolean authenticate(String usrname,String pwd) throws SQLException {
    Connection conn = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/cloudbase",user,passwd);
    try {
        PreparedStatement stm = conn.prepareStatement(
        "select * from users where email=? and password = ?");
        stm.setString(1, usrname);
        stm.setString(2, pwd);
        ResultSet result = stm.executeQuery();
        return result.next();
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            // use a logger instead of stdout
            log.info("close caused exception", e); 
        }
    }
}

这将确保抛出的异常是导致原始问题的异常。

您也可以通过这种方式来执行此操作

public class ConnectionProvider {
    public static Connection getConnection() throws SQLException {
      Connection connection = null;
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudbase"
                                                                        ,user,passwd);
      return connection;
    }

   public void authenticate(Connection connection,String usrname,String pwd) 
       throws SQLException {
    String query = "select firstName from users where email=? and password = ?";
    try {
        PreparedStatement stm = connection.prepareStatement(query);
        stm.setString(1, usrname);
        stm.setString(2, pwd);
        ResultSet result = stm.executeQuery();
        if (resultSet.next()) {
            do {
               System.out.println("Welcome, "+resultSet.getString("firstName"));
            } while(resultSet.next());
        }
       else{
           System.out.println("Username or id doesnot exist");
     }
    } catch (SQLException e) {
        System.out.println("Error :" + e.getMessage());   
    }
    finally{
       connection.close();
}

}
然后在Servlet中

protected void doPost(...) throws ServletException, IOException {
    String email = request.getParameter("email");
    String passwd = request.getParameter("pwd");
    Connection connection = ConnectionProvider.getConnection();
    new ConnectionProvider().authenticate(connection,email ,passwd);    

}

你也可以这样做

public class ConnectionProvider {
    public static Connection getConnection() throws SQLException {
      Connection connection = null;
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudbase"
                                                                        ,user,passwd);
      return connection;
    }

   public void authenticate(Connection connection,String usrname,String pwd) 
       throws SQLException {
    String query = "select firstName from users where email=? and password = ?";
    try {
        PreparedStatement stm = connection.prepareStatement(query);
        stm.setString(1, usrname);
        stm.setString(2, pwd);
        ResultSet result = stm.executeQuery();
        if (resultSet.next()) {
            do {
               System.out.println("Welcome, "+resultSet.getString("firstName"));
            } while(resultSet.next());
        }
       else{
           System.out.println("Username or id doesnot exist");
     }
    } catch (SQLException e) {
        System.out.println("Error :" + e.getMessage());   
    }
    finally{
       connection.close();
}

}
然后在Servlet中

protected void doPost(...) throws ServletException, IOException {
    String email = request.getParameter("email");
    String passwd = request.getParameter("pwd");
    Connection connection = ConnectionProvider.getConnection();
    new ConnectionProvider().authenticate(connection,email ,passwd);    

}

您尚未加载mysql驱动程序,这就是drivermanager返回null的原因。在JDBC中,我们必须在您的情况下注册DriverMysql驱动程序

  Class.forName("com.mysql.jdbc.Driver");
  Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudbase", user, passwd);
  /* your remaining code ....
   ...*/

您尚未加载mysql驱动程序,这就是drivermanager返回null的原因。在JDBC中,我们必须在您的情况下注册DriverMysql驱动程序

  Class.forName("com.mysql.jdbc.Driver");
  Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudbase", user, passwd);
  /* your remaining code ....
   ...*/

Etat HTTP 500-类型“融洽关系”异常消息描述服务商与内部服务商之间的关系符合要求。异常java.lang.NullPointerException com.cloud.db.DbConnection.authenticateDbConnection.java:25 com.cloud.db.Auth.doPostAuth.java:46 javax.servlet.http.HttpServlet.serviceHttpServlet.java:644 javax.servlet.http.HttpServlet.serviceHttpServlet.java:725 org.apache.tomcat.websocket.server.WsFilter.dofilterwssfilter.java:52抱歉我是法国人。这是我提交表单时产生的错误,代码中的哪一行是DbConnection.java:25和Auth.java:46?DbConnection.java第25行我有:PreparedStatement stm=conn.prepareStatementselect*来自email=?密码=?;java第46行:newdbconnection。authenticategoogle@cloudserver.com,谷歌;Etat HTTP 500-类型“融洽关系”异常消息描述服务商与内部服务商之间的关系符合要求。异常java.lang.NullPointerException com.cloud.db.DbConnection.authenticateDbConnection.java:25 com.cloud.db.Auth.doPostAuth.java:46 javax.servlet.http.HttpServlet.serviceHttpServlet.java:644 javax.servlet.http.HttpServlet.serviceHttpServlet.java:725 org.apache.tomcat.websocket.server.WsFilter.dofilterwssfilter.java:52抱歉我是法国人。这是我提交表单时产生的错误,代码中的哪一行是DbConnection.java:25和Auth.java:46?DbConnection.java第25行我有:PreparedStatement st m=conn.prepareStatementselect*从电子邮件=?密码=?;java第46行:newdbconnection。authenticategoogle@cloudserver.com,谷歌;