Nullpointer异常在Servlet中,但在普通类中不会发生。

huangapple go评论79阅读模式
英文:

Nullpointer exception in servlet but not in normal class

问题

以下是您提供的代码的翻译部分:

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 Successfully");
    }

    // 其他方法
}

Query类:

package register;

public class Query {
    static String create = "insert into Bank_Employees (full_name, job, wing) values (?, ?, ?)";
    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 = ?";
}

Connector类:

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;
    }
}

请注意,这只是代码的翻译部分,不包括错误修复或调试。如果您需要帮助解决问题,请提供更多详细信息,以便我可以更好地帮助您。

英文:

I am trying to run a code which creates a row in mysql database everything works well with normal classes but when I use servlets it throws a nullpointerexception I am unable to understand the reason why this is happening .

The servlet class:

package register;
import java.sql.SQLException;

import javax.servlet.annotation.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;
@WebServlet(&quot;/Create&quot;)
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(&quot;employee_name&quot;);
	String job = req.getParameter(&quot;Job&quot;);
	String wing = req.getParameter(&quot;Wing&quot;);
	try {
      RegisterModifier.create(name, job, wing);
	} catch (SQLException e) {
		e.printStackTrace();
	}
}
}

The normal class:

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

The Html form code:

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

The RegisterModifier class:
with all the methods to interact with database

    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(&quot;James&quot;,&quot;Accountant&quot;,&quot;Right&quot;);
}
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(&quot;Employee Created Succesfully&quot;);
}
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();
}
}

The Query class
The class with all the mysql queries

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

Connector class
The class which connects to the database

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

The normal test class works well and I can see the table row generated but using the servlet
throws an error 500 internal server error and says that RegisterModifier.connection is null
although it works with normal java class.

This is the error page :

HTTP Status 500 – Internal Server Error

Type Exception Report

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

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

Exception

java.lang.NullPointerException: Cannot invoke &quot;java.sql.Connection.prepareStatement(String)&quot; because &quot;register.RegisterModifier.connection&quot; 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

These are the console logs in 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 [&quot;http-nio-8080&quot;]
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 [&quot;http-nio-8080&quot;]
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.&lt;clinit&gt;(RegisterModifier.java:6)
at register.Create.&lt;clinit&gt;(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 &quot;java.sql.Connection.prepareStatement(String)&quot; because &quot;register.RegisterModifier.connection&quot; 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.&lt;clinit&gt;(RegisterModifier.java:6)
at register.Create.&lt;clinit&gt;(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 &quot;java.sql.Connection.prepareStatement(String)&quot; because &quot;register.RegisterModifier.connection&quot; 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 &quot;java.sql.Connection.prepareStatement(String)&quot; because &quot;register.RegisterModifier.connection&quot; 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)

答案1

得分: 1

在Servlet中获取数据库连接的方式与普通Java类(也称为POJO)的方式非常不同。

  1. MySQL JDBC驱动JAR文件复制到[Apache] Tomcat安装的lib子目录中。
  2. 在WAR文件的META-INF文件夹中添加文件context.xml。文件内容如下。请注意,您可以将db替换为您喜欢的任何内容,例如jdbc/ipsum
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Context&gt;
&lt;Resource name=&quot;jdbc/db&quot;
auth=&quot;Container&quot;
type=&quot;javax.sql.DataSource&quot;
driverClassName=&quot;com.mysql.jdbc.Driver&quot;
url=&quot;jdbc:mysql://localhost:3306/data2&quot;
username=&quot;root&quot;
password=&quot;Ronitpandey123&quot;
maxTotal=&quot;20&quot;
maxIdle=&quot;10&quot;
maxWaitMillis=&quot;-1&quot;/&gt;
&lt;/Context&gt;
  1. 在文件web.xml(位于WAR文件中)中添加以下[XML]元素。请注意,res-ref-name与文件context.xml中的[Resource] name匹配。
&lt;resource-ref&gt;
&lt;res-ref-name&gt;jdbc/db&lt;/res-ref-name&gt;
&lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt;
&lt;res-auth&gt;Container&lt;/res-auth&gt;
&lt;/resource-ref&gt;
  1. 在Servlet的代码中(即Create类),使用以下代码获取数据库连接。
javax.naming.Context ctx = new javax.naming.InitialContext();
javax.naming.Context envContext = (Context) ctx.lookup(&quot;java:/comp/env&quot;);
javax.sql.DataSource ds = (DataSource) envContext.lookup(&quot;jdbc/db&quot;);
java.sql.Connection conn = ds.getConnection();
英文:

The way you obtain a database connection in a servlet is very different to the way you do it with a regular Java class (also referred to as POJO).

  1. Copy MySQL JDBC driver JAR file to lib subdirectory of [Apache] Tomcat installation.
  2. Add file context.xml to META-INF folder in WAR file. File contents as follows. Note that you can replace db with whatever you like, e.g. jdbc/ipsum
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Context&gt;
&lt;Resource name=&quot;jdbc/db&quot;
auth=&quot;Container&quot;
type=&quot;javax.sql.DataSource&quot;
driverClassName=&quot;com.mysql.jdbc.Driver&quot;
url=&quot;jdbc:mysql://localhost:3306/data2&quot;
username=&quot;root&quot;
password=&quot;Ronitpandey123&quot;
maxTotal=&quot;20&quot;
maxIdle=&quot;10&quot;
maxWaitMillis=&quot;-1&quot;/&gt;
&lt;/Context&gt;
  1. Add following [XML] element to file web.xml (in WAR file). Note that res-ref-name matches [Resource] name in file context.xml, above.
&lt;resource-ref&gt;
&lt;res-ref-name&gt;jdbc/db&lt;/res-ref-name&gt;
&lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt;
&lt;res-auth&gt;Container&lt;/res-auth&gt;
&lt;/resource-ref&gt;
  1. In code of servlet (i.e. class Create), use following code to obtain database connection.
javax.naming.Context ctx = new javax.naming.InitialContext();
javax.naming.Context envContext = (Context) ctx.lookup(&quot;java:/comp/env&quot;);
javax.sql.DataSource ds = (DataSource) envContext.lookup(&quot;jdbc/db&quot;);
java.sql.Connection conn = ds.getConnection();

huangapple
  • 本文由 发表于 2023年6月5日 12:32:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403504.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定