-1

I have built maven webapp project, I create Class that extends HttpServlet, this class connect to database Mysql and get record, all dependencies I putted them in pom.xml file , but not work i tried run query in main class but it's work, and when i put any thing expect connection to database in doGet servlet method , also it's work, connection to database and get records doesn't work in doGet. Can you tell me why doesn't work ? this class that extends HttpServlet :

@WebServlet("/Home")
public class HomeClass extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = "jdbc:mysql://localhost:3306/company";
        try {
            Connection connection = DriverManager.getConnection(url,"******","*****");
            Statement statement = connection.createStatement();
            ResultSet set =  statement.executeQuery(("SELECT * FROM `users` "));
            while (set.next()){
                resp.getWriter().append(set.getString("firstname")).append(" ");
            }
        } catch (SQLException throwables) {
               resp.getWriter().append(throwables.getMessage());
        }

    }

}

dependencies in pom.xml

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
      <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.23</version>
    </dependency>


  </dependencies>

1 Answers1

-1

You need to load MySQL Driver before connection object

Class.forName("com.mysql.jdbc.Driver");

Jugal
  • 68
  • 7