Search code examples
javaservletsclassnotfoundexception

ClassNotFoundException : ValidateLogin after user enters username and password on java web application


I have created a Java web app which is just a few simple jsp pages & java classes that retrieves data from a database and displays it to one of the jsp's. The app has functionality to add, edit and remove records from the mySQL database and then update the jsp with the new input/delete. This is all working fine so I moved on to creating a login screen which would check the username & password entered in to the textfield against database records. After implementing my code and testing my app, I keep receiving an error which is "Error instantiating servlet class ValidateLogin" because of the root cause "java.lang.ClassNotFoundException: ValidateLogin". I have researched alot in to this and a lot of people seem to think that I need to add some sort of jar to my class path. After reviewing other peoples stack traces with similar errors, they all seem to have at least one line which is something to do with their own written code. I do not have this and is all pointing to apache classes.

The stack trace is as follows:

javax.servlet.ServletException: Error instantiating servlet class ValidateLogin org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:745)

root cause

java.lang.ClassNotFoundException: ValidateLogin org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:745)

Is this error appearing because of something to do with my class path? Or am I missing some obvious point that will be an easy fix?

My java classes that check the database connection and records are as follows:

ValidateLogin.java (Servlet)

 package com.dunn.helpers;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author joshuadunn
 *
 */
 public class ValidateLogin extends HttpServlet {

/**
 * 
 */
private static final long serialVersionUID = 1L;
public Connection connection;
public ResultSet results;
public String username, password, query;    
public DatabaseConnection dbConnection;

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {
        username = request.getParameter("username");
        password = request.getParameter("password");

        query = "select * from users where username = '"+username+"' and password ='"+password+"'";
        dbConnection = new DatabaseConnection();
        connection = dbConnection.setConnection();
        results = dbConnection.getResult(query,connection);

        if (results.next( ) ) {
            RequestDispatcher dispatcher = request.getRequestDispatcher("databaseEntry.jsp");
            dispatcher.forward(request, response);
            out.write(username);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    processRequest(request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    processRequest(request,response);
}

}

DatabaseConnection.java

package com.dunn.helpers;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @author joshuadunn
 *
 */
public class DatabaseConnection {

public Statement statement;
public ResultSet resultSet;
public Connection connection;

public DatabaseConnection() {

}

public Connection setConnection() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/pizzaApplication", "joshd", "joshd");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return connection;
}

public ResultSet getResult(String query, Connection conn) {
    connection = conn;
    try {
        statement = connection.createStatement();
        resultSet = statement.executeQuery(query);
    } catch (Exception e) {
        e.printStackTrace();
    }       
    return resultSet;
}
}

index.jsp is the login form page which calls on ValidateLogin

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>    
<%@ page import ="com.dunn.helpers.ValidateLogin"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">

<h1>Login</h1>

<form action ="ValidateLogin" method="POST" name="login">
<input type="text" id =username class="login-input" onblur="validateUsername();" />
<input type="text" id = password class="login-input" onblur="validatePassword();" />
<input type="submit" class="login-submit" />
<p class="login-help" ><a href="">Forgot password?</a></p>
</form>
</body>
</html>

If anyone has any ideas on what I need to do to fix this problem it would be greatly appreciated. Im fairly new to java and have never updated my classpath before. Do i need something like sbt or maven to build my project and get the jars? Or does eclipse do this automatically?

Thanks.

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<display-name>HelloWebApp</display-name>

<servlet>
<servlet-name>ValidateLogin</servlet-name> 
<servlet-class>ValidateLogin</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ValidateLogin</servlet-name>
<url-pattern>/ValidateLogin</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
    30
</session-timeout>
</session-config>
</web-app>

Solution

  • The problem is here:

    <servlet>
        <servlet-name>ValidateLogin</servlet-name> 
        <!-- HERE -->
        <servlet-class>ValidateLogin</servlet-class>
    </servlet>
    

    There's no class called ValidateLogin. In <servlet-class> you should specify the complete name of the class, this is the name of the package and the name of the class. Update this configuration into:

    <servlet>
        <servlet-name>ValidateLogin</servlet-name> 
        <!-- HERE -->
        <servlet-class>com.dunn.helpers.ValidateLogin</servlet-class>
    </servlet>
    

    A better option will be to create a web application that uses Servlet 3.0 or superior, noticed by this part of your configuration:

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        id="WebApp_ID" version="2.5">
    

    If you see, there's version="2.5" and there are references to 2.5 (or 2_5) in it. Change it to:

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0">
    

    And you can forget about defining the servlets in web.xml, instead use annotations:

    //this annotation works like <servlet> and <servlet-mapping> together
    @WebServlet("/ValidateLogin")
    public class ValidateLogin extends HttpServlet {
        //class definition
    }