我正在运行我的 servlet RegistrationServlet
,并尝试创建一个 Database 对象
这是小服务程序:
@WebServlet("/register")
public class RegistrationServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
// create a new connection to mysql database , with this we put the new client in the database
Database myDabatase = null;
try {
myDabatase = new Database();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} // create a new database
myDabatase.createDatabaseAndTables(); // create the tables of the database
HttpSession session = request.getSession();
synchronized(session)
{
boolean returnValue = myDabatase.addNewClient("david", "cole", "jamie", "123456789", "johnny", "blabla");
if (returnValue == true) // client was added
{
String addressPath = "/WEB-INF/results/show-name.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(addressPath);
dispatcher.forward(request, response);
}
else if (returnValue == false) // client was not added becuase he's already registered
{
}
}
}
}
这是完整的课程:
但是当我在我的 servlet 中执行该行时:
boolean returnValue = myDabatase.addNewClient("david", "cole", "jamie", "123456789", "johnny", "blabla");
我得到一个 NullPointerException 说:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at db.Database.<init>(Database.java:18)
at servlets.RegistrationServlet.doGet(RegistrationServlet.java:28)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
这导致我上线:
Class.forName("com.mysql.jdbc.Driver");
在Database
类的构造函数中,正如您在跟踪中看到的那样:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
但是,当我执行与主程序相同的程序时:
public class Main {
public static void main(String [ ] args) throws Exception
{
Database myConnection = new Database();
myConnection.createDatabaseAndTables();
boolean returnValue = myConnection.addNewClient("david", "cole", "jamie", "123456789", "johnny", "blabla");
}
}
一切都很好,我没有得到 NullPointerException 。
那么如果我从一个 servelt 做同样的事情有什么问题呢?为什么 NullPointerException ?
问候