英文:
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("/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();
}
}
}
The normal class:
package register;
import java.sql.SQLException;
public class Test {
public static void main (String main[]) throws SQLException
{
RegisterModifier.create("James", "Accountant","Right");
}
}
The Html form code:
<!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>
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("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();
}
}
The Query class
The class with all the mysql queries
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 = ?";
}
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 = "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;
}
}
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 "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
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 ["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)
答案1
得分: 1
在Servlet中获取数据库连接的方式与普通Java类(也称为POJO)的方式非常不同。
- 将MySQL JDBC驱动JAR文件复制到[Apache] Tomcat安装的
lib
子目录中。 - 在WAR文件的
META-INF
文件夹中添加文件context.xml
。文件内容如下。请注意,您可以将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>
- 在文件
web.xml
(位于WAR文件中)中添加以下[XML]元素。请注意,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>
- 在Servlet的代码中(即
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();
英文:
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).
- Copy MySQL JDBC driver JAR file to
lib
subdirectory of [Apache] Tomcat installation. - Add file
context.xml
toMETA-INF
folder in WAR file. File contents as follows. Note that you can replace db with whatever you like, e.g. 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>
- Add following [XML] element to file
web.xml
(in WAR file). Note thatres-ref-name
matches [Resource
]name
in filecontext.xml
, above.
<resource-ref>
<res-ref-name>jdbc/db</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
- 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("java:/comp/env");
javax.sql.DataSource ds = (DataSource) envContext.lookup("jdbc/db");
java.sql.Connection conn = ds.getConnection();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论