eclipse servlet中出现空指针异常,但普通类中没有

gopyfrb3  于 2023-06-05  发布在  Eclipse
关注(0)|答案(1)|浏览(226)

我试图运行一个代码,在mysql数据库中创建一行,一切都与正常的类工作得很好,但当我使用servlet时,它抛出了一个nullpointerexception,我无法理解为什么会发生这种情况。
servlet类:

package register;
import java.sql.SQLException;

import javax.servlet.annotation.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;
@WebServlet("/Create")
public class Create extends HttpServlet {
    private static final long serialVersionUID = 183957L;
    static RegisterModifier rm = new RegisterModifier();
public void service(HttpServletRequest req,HttpServletResponse res) {
    String name = req.getParameter("employee_name");
    String job = req.getParameter("Job");
    String wing = req.getParameter("Wing");
    try {
      RegisterModifier.create(name, job, wing);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
}

普通类:

package register;
import java.sql.SQLException;
public class Test {
public static void main (String main[]) throws SQLException
    {
        RegisterModifier.create("James", "Accountant","Right");
    }
    }

Html表单代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="backicon.ico">
    <title>Create Employee Data</title>
</head>
<body>
  <form action="Create">
    <hr>
<input type="text" name = "employee_name"  placeholder="Enter the employee's full name"> 
<br>
<input type="radio" class="Left Wing"  name="Wing">Left Wing
<br>
<input type="radio" value="Right Wing"  name="Wing">Right Wing
<br>
<select name="Job">
    <option value="">choose the job</option>
    <option value="Clerk">Clerk</option>
    <option value="Accountant">Accountant</option>
    <option value="Cook">Cook</option>
    <option value="Janitor">Janitor</option>
    <option value="Caterer">Caterer</option>
    <option value="Supervisor">Supervisor</option> 
</select>
<br>
<input type="submit">
  </form>  
</body>
</html>

RegisterModifier类:与数据库交互的所有方法

package register;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class RegisterModifier {
static  Connection connection = Connector.getConnection();
public static void main(String args) throws SQLException {
    create("James","Accountant","Right");
}
static PreparedStatement pstm;
public static void create(String name,String job,String wing) throws SQLException {
    pstm = connection.prepareStatement(Query.create);
    pstm.setString(1,name);
    pstm.setString(2,job);
    pstm.setString(3,wing);
    pstm.execute();
    System.out.println("Employee Created Succesfully");
}
public static void updateName(int id,String name) throws SQLException {
pstm = connection.prepareStatement(Query.updateName);
pstm.setString(1,name);
pstm.setInt(2,id);
}
public void updateJob(int id,String job) throws SQLException 
{
 pstm = connection.prepareStatement(Query.updateJob);
pstm.setString(1,job);
pstm.setInt(2, id);

}
public void updateWing(int id ,String wing) throws SQLException 
{   pstm = connection.prepareStatement(Query.updatewing);
    pstm.setString(1,wing);
    pstm.setInt(2, id);
    pstm.execute();

}
public void read() throws SQLException
{
    pstm = connection.prepareStatement(Query.read);
    pstm.execute();
}
public void read(int id) throws SQLException
{
    pstm = connection.prepareStatement(Query.readById);
    pstm.setInt(1, id);
    pstm.execute();
}
public void read(String name) throws SQLException
{
    pstm = connection.prepareStatement(Query.readById);
    pstm.setString(1, name);
    pstm.execute();
}

public void delete(int id)throws SQLException
{
pstm = connection.prepareStatement(Query.delete);
pstm.setInt(1,id);
pstm.execute();
}
}

Query类包含所有mysql查询的类

package register;
public class Query
    {
        
        static String create ="insert into Bank_Employees (full_name,job,wing) value(?,?,?)";
        static String updateName = "update Bank_Employees set full_name = ? where id= ?";
        static String updateJob = "update Bank_Employees set job = ? where id= ?";
        static String updatewing = "update Bank_Employees set wing = ? where id= ?";
        static String read = "Select * from Bank_Employees ";
        static String readById = "Select  from Bank_Employees where id = ? ";
        static String readByName = "Select  from Bank_Employees where full_name = ?";
        static String delete = "Delete from Bank_Employees where id = ?";
    
    }

连接器类连接到数据库的类

package register;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connector {
static String url = "jdbc:mysql://localhost:3306/";
static String Database1="data2";
static String user = "root";
static String password = "Ronitpandey123";
static Connection con;
public static Connection getConnection()
{
    try {
        con = DriverManager.getConnection(url+Database1,user,password);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return con;
}
}

正常的测试类工作良好,我可以看到生成的表行,但使用servlet抛出一个错误500内部服务器错误,并说RegisterModifier.connection是null,尽管它与正常的java类一起工作。
404错误页面

HTTP Status 500 – Internal Server Error

Type Exception Report

Message Cannot invoke "java.sql.Connection.prepareStatement(String)" because "register.RegisterModifier.connection" is null

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

java.lang.NullPointerException: Cannot invoke "java.sql.Connection.prepareStatement(String)" because "register.RegisterModifier.connection" is null
    register.RegisterModifier.create(RegisterModifier.java:12)
    register.Create.service(Create.java:16)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:779)
    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.
Apache Tomcat/9.0.71

下面是eclipse ide中的控制台日志:

Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name:   Apache Tomcat/9.0.71
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Jan 9 2023 22:33:01 UTC
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version number: 9.0.71.0
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 11
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.0
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Users\dkent\eclipse\plugins\org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.7.v20230425-1502\jre
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           17.0.7+7
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Eclipse Adoptium
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\Users\dkent\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:\servers for java ee jdk 19\apache-tomcat-9.0.71
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\dkent\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\servers for java ee jdk 19\apache-tomcat-9.0.71
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\dkent\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: --add-opens=java.base/java.lang=ALL-UNNAMED
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: --add-opens=java.base/java.io=ALL-UNNAMED
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: --add-opens=java.base/java.util=ALL-UNNAMED
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: --add-opens=java.base/java.util.concurrent=ALL-UNNAMED
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Jun 05, 2023 9:24:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -XX:+ShowCodeDetailsInExceptionMessages
Jun 05, 2023 9:24:39 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The Apache Tomcat Native library which allows using OpenSSL was not found on the java.library.path: [C:\Users\dkent\eclipse\plugins\org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.7.v20230425-1502\jre\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Users/dkent/eclipse//plugins/org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.7.v20230425-1502/jre/bin/server;C:/Users/dkent/eclipse//plugins/org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.7.v20230425-1502/jre/bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\dkent\AppData\Local\Microsoft\WindowsApps;;C:\Users\dkent\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\dkent\eclipse;;.]
Jun 05, 2023 9:24:40 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Jun 05, 2023 9:24:40 AM org.apache.catalina.startup.Catalina load
INFO: Server initialization in [595] milliseconds
Jun 05, 2023 9:24:40 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
Jun 05, 2023 9:24:40 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.71]
Jun 05, 2023 9:24:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Jun 05, 2023 9:24:40 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in [473] milliseconds
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/data2
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:706)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:229)
    at register.Connector.getConnection(Connector.java:14)
    at register.RegisterModifier.<clinit>(RegisterModifier.java:6)
    at register.Create.<clinit>(Create.java:10)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:150)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1067)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:787)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:118)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:891)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1784)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)
Jun 05, 2023 9:24:56 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [register.Create] in context with path [/BankEmployeeRegister] threw exception
java.lang.NullPointerException: Cannot invoke "java.sql.Connection.prepareStatement(String)" because "register.RegisterModifier.connection" is null
    at register.RegisterModifier.create(RegisterModifier.java:12)
    at register.Create.service(Create.java:16)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:779)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:891)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1784)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)

Jun 05, 2023 9:34:41 AM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/BankEmployeeRegister] has started
Jun 05, 2023 9:34:41 AM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/BankEmployeeRegister] is completed
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/data2
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:706)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:229)
    at register.Connector.getConnection(Connector.java:14)
    at register.RegisterModifier.<clinit>(RegisterModifier.java:6)
    at register.Create.<clinit>(Create.java:10)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:150)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1067)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:787)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:118)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:891)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1784)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)
Jun 05, 2023 9:45:59 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [register.Create] in context with path [/BankEmployeeRegister] threw exception
java.lang.NullPointerException: Cannot invoke "java.sql.Connection.prepareStatement(String)" because "register.RegisterModifier.connection" is null
    at register.RegisterModifier.create(RegisterModifier.java:12)
    at register.Create.service(Create.java:16)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:779)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:891)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1784)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)

Jun 05, 2023 9:46:02 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [register.Create] in context with path [/BankEmployeeRegister] threw exception
java.lang.NullPointerException: Cannot invoke "java.sql.Connection.prepareStatement(String)" because "register.RegisterModifier.connection" is null
    at register.RegisterModifier.create(RegisterModifier.java:12)
    at register.Create.service(Create.java:16)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:779)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:891)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1784)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)
hk8txs48

hk8txs481#

在servlet中获得数据库连接的方式与使用常规Java类(也称为POJO)获得数据库连接的方式非常不同。
1.将MySQL JDBC driver JAR file复制到[Apache] Tomcat安装的lib子目录。
1.将文件context.xml添加到WAR文件中的META-INF文件夹。文件内容如下。注意,你可以用任何你喜欢的东西替换 db,例如jdbc/ipsum

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource name="jdbc/db"
              auth="Container"
              type="javax.sql.DataSource"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/data2"
              username="root"
              password="Ronitpandey123"
              maxTotal="20"
              maxIdle="10"
              maxWaitMillis="-1"/>
</Context>

1.将以下[XML]元素添加到文件web.xml(在WAR文件中)。请注意,res-ref-name匹配上面文件context.xml中的[Resource] name

<resource-ref>
    <res-ref-name>jdbc/db</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

1.在servlet的代码中(即class Create),使用以下代码获取数据库连接。

javax.naming.Context ctx = new javax.naming.InitialContext();
javax.naming.Context envContext = (Context) ctx.lookup("java:/comp/env");
javax.sql.DataSource ds = (DataSource) envContext.lookup("jdbc/db");
java.sql.Connection conn = ds.getConnection();

相关问题