1

I have created the following project in Eclipse

with my web.xml looking like so:

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>CustomerServlet</servlet-name>
    <display-name>CustomerServlet</display-name>
    <description></description>
    
    <servlet-class>com.acn.controller.CustomerServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CustomerServlet</servlet-name>
    <url-pattern>/register</url-pattern>
  </servlet-mapping>
</web-app>

and my Servlet Class looking like so:

package com.acn.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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.acn.dao.CustomerDao;
import com.acn.registration.Customer;

/**
 * Servlet implementation class CustomerServlet
 */
//@WebServlet("/register")
//@WebServlet( name="ListServlet", displayName="ListServlet", urlPatterns = {"/register"}, loadOnStartup=1)
public class CustomerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private CustomerDao customerDao;
    
    public void init() {
        customerDao = new CustomerDao();
    }
       
 

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.getWriter().append("Served at: ").append(request.getContextPath());
        
        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/customerregister.jsp");
        dispatcher.forward(request, response);
    } 

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String address = request.getParameter("address");
        String contact = request.getParameter("contact");
        
        Customer customer = new Customer();
        customer.setFirstName(firstName);
        customer.setLastName(lastName);
        customer.setUsername(username);
        customer.setPassword(password);
        customer.setAddress(address);
        customer.setContact(contact);
        
        try {
        customerDao.registerCustomer(customer);
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        response.sendRedirect("customerdetails.jsp");
        //RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/customerdetails.jsp");
        //dispatcher.forward(request, response);
    }

}
package com.acn.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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.acn.dao.CustomerDao;
import com.acn.registration.Customer;

/**
 * Servlet implementation class CustomerServlet
 */
//@WebServlet("/register")
//@WebServlet( name="ListServlet", displayName="ListServlet", urlPatterns = {"/register"}, loadOnStartup=1)
public class CustomerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private CustomerDao customerDao;
    
    public void init() {
        customerDao = new CustomerDao();
    }
       
 

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.getWriter().append("Served at: ").append(request.getContextPath());
        
        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/customerregister.jsp");
        dispatcher.forward(request, response);
    } 

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String address = request.getParameter("address");
        String contact = request.getParameter("contact");
        
        Customer customer = new Customer();
        customer.setFirstName(firstName);
        customer.setLastName(lastName);
        customer.setUsername(username);
        customer.setPassword(password);
        customer.setAddress(address);
        customer.setContact(contact);
        
        try {
        customerDao.registerCustomer(customer);
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        response.sendRedirect("customerdetails.jsp");
        //RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/customerdetails.jsp");
        //dispatcher.forward(request, response);
    }

}

my CustomerDao looks like so:

package com.acn.dao;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.acn.registration.Customer;


public class CustomerDao {
    private ConnectorPool conPool;
    
    public CustomerDao(ConnectorPool cpool) {
        if(cpool == null) {
            throw new IllegalArgumentException(" pool should not be null");
        }
        conPool = cpool;
    }
    
    
    public void registerCustomer(Customer cust) {
        String sql = "insert into customer (first_name, last_name, username, password, address, contact) values (?,?,?,?,?,?)";
        
        try(Connection con = conPool.getMyConnection()) {
            PreparedStatement pstm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            con.setAutoCommit(false); //starting transaction
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            pstm.setString(1, cust.getFirstName());
            pstm.setString(2, cust.getLastName());
            pstm.setString(3, cust.getUsername());
            pstm.setString(4, cust.getPassword());
            pstm.setString(5, cust.getAddress());
            pstm.setString(6, cust.getContact());
            
            int numOfRows = pstm.executeUpdate();
            
            //Führt zur id in meiner API
            //Prüf ob id==0 denn das darf nicht sein
            ResultSet rs = pstm.getGeneratedKeys();
            System.out.println(numOfRows);
            
            if(rs.next()) {
                cust.setId(rs.getLong(1));
            }
            
            System.out.println(cust);
            
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
        
        
    }
        
    }

and my jsp being the following:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <div align="center">
  <h1>Employee Register Form</h1>
  <form action="<%= request.getContextPath() %>/register" method="post">
   <table style="with: 80%">
    <tr>
     <td>First Name</td>
     <td><input type="text" name="firstName" /></td>
    </tr>
    <tr>
     <td>Last Name</td>
     <td><input type="text" name="lastName" /></td>
    </tr>
    <tr>
     <td>UserName</td>
     <td><input type="text" name="username" /></td>
    </tr>
    <tr>
     <td>Password</td>
     <td><input type="password" name="password" /></td>
    </tr>
    <tr>
     <td>Address</td>
     <td><input type="text" name="address" /></td>
    </tr>
    <tr>
     <td>Contact No</td>
     <td><input type="text" name="contact" /></td>
    </tr>
   </table>
   <input type="submit" value="Submit" />
  </form>
 </div>
</body>
</html>

The index.jsp file is running fine and I get the page displayed using http://localhost:8080/RegistrationWebApp/

However trying http://localhost:8080/RegistrationWebApp/register gives me the error:

java.lang.NoClassDefFoundError: javax/servlet/http/HttpServlet
java.lang.ClassLoader.defineClass1(Native Method)
java.lang.ClassLoader.defineClass(ClassLoader.java:756)
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2470)
org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:866)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1370)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1224)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:353)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:870)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1696)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:748)

I have looked already at other posts and tried to implement suggested solutions, but without any success so far. Could anyone help me out please?

EDIT: my pom dependencies:

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
        <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
    
    

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-juli -->
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-juli</artifactId>
        <version>10.0.5</version>
    </dependency>
    
    
    <!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>3.10.0</version>
        <scope>test</scope>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.9.0</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.8.0</version>
    </dependency>
    
    

  </dependencies>
CatiaV5
  • 168
  • 1
  • 1
  • 10
  • What is `CustomerDao`? Can the constructor of this class throw an exception? – dan1st Jun 14 '21 at 15:11
  • The details of the exception must be in the logs. Please add the complete stacktrace of the error to your question. Which version of Tomcat are you using? – Piotr P. Karwasz Jun 14 '21 at 15:25
  • @dan1st : copied the CustomerDao file in here too. but tested it and it seems to be working fine – CatiaV5 Jun 15 '21 at 10:23
  • @PiotrP.Karwasz : I copied the stacktrace now and Im using Tomcat v10.0 – CatiaV5 Jun 15 '21 at 10:24
  • 1
    Does this answer your question? [jakarta.servlet.ServletException: Class \[com.practice.MyServlet\] is not a Servlet](https://stackoverflow.com/questions/65872072/jakarta-servlet-servletexception-class-com-practice-myservlet-is-not-a-servle) – Piotr P. Karwasz Jun 15 '21 at 10:28
  • TL;DR: Tomcat 10 is a Jakarta EE 9 server, you need to use the `jakarta.servlet` package prefix instead of `javax.servlet`. Replace the `javax.servlet-api` dependency with [`jakarta.servlet-api`](https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api/5.0.0) version `5.0.0`. – Piotr P. Karwasz Jun 15 '21 at 10:29
  • The `CustomerDao` doesn't fit your servlet. The servlet calls the no-args-constructor while `CustomerDao` only provides a constructor with an argument. – dan1st Jun 15 '21 at 10:32
  • You are using Tomcat 10 which is JakartaEE, either downgrade to Tomcat 9, or upgrade your dependencies to JakartaEE dependencies and fix the imports. Either way will work. – M. Deinum Jun 15 '21 at 10:49
  • @PiotrP.Karwasz yes, this is indeed the answer to my problem.....Thank you so much :) – CatiaV5 Jun 15 '21 at 11:08

0 Answers0