当前位置: 首页 > 知识库问答 >
问题:

无法调用“java.sql.Connection.prepareStatement(字符串)”,因为“Connection”为空

濮宇定
2023-03-14

我一直得到这个错误在我的eclipse说Jan26, 2021 12:58:03AMorg.apache.catalina.core.标准WrapperValve调用SEVERE: Servlet.service()servlet[com.xadmin.usermanagement.web.UserServlet]在上下文中与路径[/UserManagement]抛出异常<--plhd-不能调用java.sql.Connection.prepare语句(字符串),因为连接为空

错误

INFO: Server version name:   Apache Tomcat/8.5.61
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Dec 3 2020 14:03:28 UTC
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version number: 8.5.61.0
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 10
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.0
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Users\ACER\Desktop\eclipse-jee-2020-12-R-win32-x86_64\eclipse\plugins\org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_15.0.1.v20201027-0507\jre
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           15.0.1+9-18
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\Users\ACER\eclipse-workspace\myServlet\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:\Program Files\Apache Software Foundation\Tomcat 8.5
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\ACER\eclipse-workspace\myServlet\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 8.5
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\ACER\eclipse-workspace\myServlet\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Jan 26, 2021 12:57:33 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -XX:+ShowCodeDetailsInExceptionMessages
Jan 26, 2021 12:57:33 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\ACER\Desktop\eclipse-jee-2020-12-R-win32-x86_64\eclipse\plugins\org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_15.0.1.v20201027-0507\jre\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Users/ACER/Desktop/eclipse-jee-2020-12-R-win32-x86_64/eclipse//plugins/org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_15.0.1.v20201027-0507/jre/bin/server;C:/Users/ACER/Desktop/eclipse-jee-2020-12-R-win32-x86_64/eclipse//plugins/org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_15.0.1.v20201027-0507/jre/bin;C:\Program Files\AdoptOpenJDK\jdk-8.0.252.09-hotspot\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:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files\nodejs\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Brackets\command;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Users\ACER\AppData\Local\Microsoft\WindowsApps;C:\Users\ACER\AppData\Roaming\npm;C:\Users\ACER\Desktop\eclipse-jee-2020-12-R-win32-x86_64\eclipse;;.]
Jan 26, 2021 12:57:34 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8089"]
Jan 26, 2021 12:57:34 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jan 26, 2021 12:57:34 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 818 ms
Jan 26, 2021 12:57:34 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
Jan 26, 2021 12:57:34 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.5.61
Jan 26, 2021 12:57:35 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jan 26, 2021 12:57:35 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8089"]
Jan 26, 2021 12:57:35 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1295 ms
INSERT INTO users  (name, email, country) VALUES  (?, ?, ?);
java.sql.SQLException: The server time zone value 'unknown' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
    at com.xadmin.usermanagement.dao.UserDao.getConnection(UserDao.java:35)
    at com.xadmin.usermanagement.dao.UserDao.insertUser(UserDao.java:49)
    at com.xadmin.usermanagement.web.UserServlet.insertUser(UserServlet.java:107)
    at com.xadmin.usermanagement.web.UserServlet.doGet(UserServlet.java:54)
    at com.xadmin.usermanagement.web.UserServlet.doPost(UserServlet.java:39)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:616)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1634)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value 'unknown' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
    at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132)
    at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2234)
    at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2258)
    at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
    ... 34 more
Jan 26, 2021 12:58:03 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.xadmin.usermanagement.web.UserServlet] in context with path [/UserManagement] threw exception
java.lang.NullPointerException: Cannot invoke "java.sql.Connection.prepareStatement(String)" because "connection" is null
    at com.xadmin.usermanagement.dao.UserDao.insertUser(UserDao.java:50)
    at com.xadmin.usermanagement.web.UserServlet.insertUser(UserServlet.java:107)
    at com.xadmin.usermanagement.web.UserServlet.doGet(UserServlet.java:54)
    at com.xadmin.usermanagement.web.UserServlet.doPost(UserServlet.java:39)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:616)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1634)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:832)

用户道


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.xadmin.usermanagement.bean.User;

public class UserDao {

    private String jdbcURL = "jdbc:mysql://localhost/userdb?";
    private String jdbcUsername = "root";
    private String jdbcPassword = "";
    private String jdbcDriver = "com.mysql.cj.jdbc.Driver";
    
    private static final String INSERT_USERS_SQL = "INSERT INTO users" + "  (name, email, country) VALUES "
            + " (?, ?, ?);";

    private static final String SELECT_USER_BY_ID = "select id,name,email,country from users where id =?";
    private static final String SELECT_ALL_USERS = "select * from users";
    private static final String DELETE_USERS_SQL = "delete from users where id = ?;";
    private static final String UPDATE_USERS_SQL = "update users set name = ?,email= ?, country =? where id = ?;";
    
    public UserDao() {
    }
    
    protected Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName(jdbcDriver);
            connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return connection;
}
    
    public void insertUser(User user) throws SQLException {
        System.out.println(INSERT_USERS_SQL);
        // try-with-resource statement will auto close the connection.
        try (Connection connection = getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
            preparedStatement.setString(1, user.getName());
            preparedStatement.setString(2, user.getEmail());
            preparedStatement.setString(3, user.getCountry());
            System.out.println(preparedStatement);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            printSQLException(e);
        }
    }
    
    public User selectUser(int id) {
        User user = null;
        // Step 1: Establishing a Connection
        try (Connection connection = getConnection();
                // Step 2:Create a statement using connection object
                PreparedStatement preparedStatement = connection.prepareStatement(SELECT_USER_BY_ID)) {
            preparedStatement.setInt(1, id);
            System.out.println(preparedStatement);
            // Step 3: Execute the query or update query
            ResultSet rs = preparedStatement.executeQuery();

            // Step 4: Process the ResultSet object.
            while (rs.next()) {
                String name = rs.getString("name");
                String email = rs.getString("email");
                String country = rs.getString("country");
                user = new User(id, name, email, country);
            }
        } catch (SQLException e) {
            printSQLException(e);
        }
        return user;
    }
    
    public List<User> selectAllUsers() {

        // using try-with-resources to avoid closing resources (boiler plate code)
        List<User> users = new ArrayList<>();
        // Step 1: Establishing a Connection
        try (Connection connection = getConnection();

                // Step 2:Create a statement using connection object
            PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_USERS)) {
            System.out.println(preparedStatement);
            // Step 3: Execute the query or update query
            ResultSet rs = preparedStatement.executeQuery();

            // Step 4: Process the ResultSet object.
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                String country = rs.getString("country");
                users.add(new User(id, name, email, country));
            }
        } catch (SQLException e) {
            printSQLException(e);
        }
        return users;
    }
    
    public boolean updateUser(User user) throws SQLException {
        boolean rowUpdated;
        try (Connection connection = getConnection();
                PreparedStatement statement = connection.prepareStatement(UPDATE_USERS_SQL)) {
            System.out.println("updated USer:"+statement);
            statement.setString(1, user.getName());
            statement.setString(2, user.getEmail());
            statement.setString(3, user.getCountry());
            statement.setInt(4, user.getId());

            rowUpdated = statement.executeUpdate() > 0;
        }
        return rowUpdated;
    }
    
    public boolean deleteUser(int id) throws SQLException {
        boolean rowDeleted;
        try (Connection connection = getConnection();
                PreparedStatement statement = connection.prepareStatement(DELETE_USERS_SQL)) {
            statement.setInt(1, id);
            rowDeleted = statement.executeUpdate() > 0;
        }
        return rowDeleted;
    }
    
    private void printSQLException(SQLException ex) {
        for (Throwable e : ex) {
            if (e instanceof SQLException) {
                e.printStackTrace(System.err);
                System.err.println("SQLState: " + ((SQLException) e).getSQLState());
                System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
                System.err.println("Message: " + e.getMessage());
                Throwable t = ex.getCause();
                while (t != null) {
                    System.out.println("Cause: " + t);
                    t = t.getCause();
                }
            }
        }
    }
    
}

用户servlet


import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xadmin.usermanagement.bean.User;
import com.xadmin.usermanagement.dao.UserDao;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/")
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       private UserDao userDao;
    

    /**
     * @see Servlet#init(ServletConfig)
     */
    public void init() throws ServletException {
        userDao = new UserDao();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
    
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getServletPath();

            switch (action) {
            case "/new":
                showNewForm(request, response);
                break;
            case "/insert":
                try {
                    insertUser(request, response);
                } catch (SQLException | IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                    break;
            case "/delete":
                try {
                    deleteUser(request, response);
                } catch (SQLException | IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                break;
            case "/edit":
                try {
                    showEditForm(request, response);
                } catch (SQLException | ServletException | IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                break;
            case "/update":
                try {
                    updateUser(request, response);
                } catch (SQLException | IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                break;
            default:
                try {
                    listUser(request, response);
                } catch (SQLException | IOException | ServletException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            }
    }
        
        private void showNewForm(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
            dispatcher.forward(request, response);
        }
        
        private void insertUser(HttpServletRequest request, HttpServletResponse response) 
                throws SQLException, IOException {
            String name = request.getParameter("name");
            String email = request.getParameter("email");
            String country = request.getParameter("country");
            User newUser = new User(name, email, country);
                userDao.insertUser(newUser);
            response.sendRedirect("list");
        }
        
        private void deleteUser(HttpServletRequest request, HttpServletResponse response) 
                throws SQLException, IOException {
            int id = Integer.parseInt(request.getParameter("id"));
            try {
                userDao.deleteUser(id);
            }catch (Exception e) {
                e.printStackTrace();
            }
            response.sendRedirect("list");

        }
        
        private void showEditForm(HttpServletRequest request, HttpServletResponse response)
                throws SQLException, ServletException, IOException {
            int id = Integer.parseInt(request.getParameter("id"));
            
                User existingUser = userDao.selectUser(id);
                try {
                    RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
                    request.setAttribute("user", existingUser);
                     dispatcher.forward(request, response);
                }catch (Exception e) {
                    e.printStackTrace();
                }

        }
        
        private void updateUser(HttpServletRequest request, HttpServletResponse response) 
                throws SQLException, IOException {
            int id = Integer.parseInt(request.getParameter("id"));
            String name = request.getParameter("name");
            String email = request.getParameter("email");
            String country = request.getParameter("country");

            User book = new User(id, name, email, country);
                userDao.updateUser(book);
            response.sendRedirect("list");
        }
        
        private void listUser(HttpServletRequest request, HttpServletResponse response)
                throws SQLException, IOException, ServletException {
            try {
                List<User> listUser = userDao.selectAllUsers();
                request.setAttribute("listUser", listUser);
                RequestDispatcher dispatcher = request.getRequestDispatcher("user-list.jsp");
                dispatcher.forward(request, response);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

共有1个答案

郭盛
2023-03-14

您可以尝试对代码进行以下更改吗?

私有字符串jdbcURL=“jdbc:mysql://localhost/userdb?";

请在localhost之后添加端口号,然后删除?最后

jdbc:mysql://localhost:3306/userdb

注意:如果在安装MySQL时更改了端口号,请更改3306端口。

 类似资料:
  • 我在eclipse上不断收到这个错误,说Jan 26 2021年12:58:03 AM org.apache.catalina.core.StandardWrapperValve invoke Severe:servlet.Service()for servlet[com.xadmin.userManagement.web.userServlet]在路径为[/UserManagement]的上下文

  • 这里有两节课。SaleGood类有一个可变特性a,应该在另一个名为Inventory类中使用。类Inventory有两个可变特性,inventoryAmount和inventoryBill,这两个特性都应该在类Salegood中使用。 我正在使用getter/setter。然而,错误说 我以为是因为这个代码错了?因此我不能使用。我试了一整天。但仍然不知道如何修复它。我尝试了,也是错误的。 在课堂上

  • 我刚来spring boot,就偶然发现了这个奇怪的例外。 目的:我正在尝试构建一个基本的spring boot rest客户端应用程序。 问题:获取异常为空的错误。即 当我的@RequestMapping值为“Employee”时, 但当我将其改为“模板/员工”时, 它会抛出下面附加的错误。谁能找出并解释是什么引起了这个问题?谢谢. 错误 这里是我的pom.xml以供参考 error.jsp

  • 我正在尝试编写一个简单的客户机/服务器应用程序。我在客户端有一个数据,它会变成一个整数数组并传输到服务器。服务器进行计算并将其返回给客户端。但我的程序却出现了这个例外。 抱歉,我只是在学习,真的需要你的帮助。

  • 问题内容: 您如何将此String转换为gson.JsonArray? 这是我的代码: 这是将这个Collections字符串转换为JSonArray的方法吗? 问题答案: 要在JSON数组中包含字符串值,必须记住在Java程序中用反斜杠转义双引号。请参见下面的声明。 您在main()方法中的代码可以正常工作。以下只是对main()方法中的代码的微小修改。 最后,请记住在语句“ com.googl

  • 我将XML作为字符串传递给一个方法,并再次将其转换为XML来完成我的工作。 其正常工作正常,但当出现特殊字符时,如<代码> 我的XML字符串: 我的代码是: 错误: “=”是意外标记。预期标记为“;”。第1行,位置150。 完全错误为: 系统Xml。XmlException未由用户代码处理HResult=-2146232000消息=“=”是意外令牌。预期标记为“;”。第1行,位置150。源=系统。