jspservletshttp-status-code-404

404 error when redirecting to Servlet from a html page


So I'm trying to create a WebApp on InteliJ Ultimate about a telecom website and I wanna get familiar with servlets but i can't get them to work properly

<!DOCTYPE html>
<html>
<head>
    <title>Login Page</title>
</head>
<body>
    <h2>Login Form</h2>
    <form action="LoginServ" method="post">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username"><br>
        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password"><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

this is my index.html (basic login page) that im trying to redirect to the login servlet to then show 1 of 3 different dashboards (clientDashboard, salesmanDashboard and adminDashboard) depending on a value inserted in a MySQL database

I've tried following different tutorials on how to use servlets couldn't get anything to work and now I'm just at a point where I just don't know what to do anymore

Edit 1: I keep getting Error 404 Not found when I redirect from the html page to the servlet which seems odd to me seeing as how I have the servlet file LoginServ.java in the directory along with this line of code in the index file <form action="LoginServ" method="post"> which I am pretty sure searches for a file with that name (don't quote me on that I'm still new to web dev)

At this points im just trying to get the redirect to work at all

package servlets;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws ServletException, IOException {
        response.sendRedirect(request.getContextPath() + "/salesmanDashboard.jsp");
    }
}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>Ergasia2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>Ergasia 2</name>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.target>11</maven.compiler.target>
        <maven.compiler.source>11</maven.compiler.source>
        <junit.version>5.10.0</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>jakarta.platform</groupId>
            <artifactId>jakarta.jakartaee-api</artifactId>
            <version>9.0.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>3.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>3.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-cdi2-se</artifactId>
            <version>3.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.weld.se</groupId>
            <artifactId>weld-se-core</artifactId>
            <version>5.1.2.Final</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.4.0</version>
            </plugin>
        </plugins>
    </build>
</project>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://jakarta.ee/xml/ns/jakartaee" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" version="6.0">
  <servlet>
    <description/>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>servlets.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <display-name>Ergasia 2</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

I'm using Apache Tomcat 10.1.24 When i was creating the project i selected "Jakarta EE" as the Project Generator with Maven as the build sustem, also im using Oracle OpenJDK 22.0.1

My directory looks like this:

Project1
-src
  -main 
    -java
      -servlets
        - LoginServlet
  -resources
    - META-INF
      - index.html
  -webapp
    - WEB-INF
      - salesmanDashboard.jsp

Edit 2: The problem looks to be that the servlet mapping i had written in the web.xml file interfered with the @WebServlet("/LoginServlet") that was in the Servlet i was trying to run. I don't understand why but it did and removing the

<servlet>
    <description/>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>servlets.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>

From the web.xml file seemed to fix it

Edit 3: I know it's been about a year since I've edited anything on this question but i'll be frank i don't understand how redirecting works.

I've racked my brain over this for about another week since starting another project similar to this. and i gotta say im having the exact same issues.

if i just redirect from html page to another html page it works just fine. The second i try to redirect from within the servlet i suddenly just get "error 404".

Odd part is i have this line of code which is executed normally without any problems.

response.sendRedirect("register.html?error=missingFields");

I assume this is working because the page doesn't "change" per say. the url on my browser doesn't change when this error is supposed to be shown on screen.

However when this redirect is supposed to happen response.sendRedirect(request.getContextPath() + "/login.html"); i get the Error.

I've looked throught a couple of other questions/websites that seemed related such as: My jsp cannot find my servlet, giving me a 404 , Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available" and Servlet Returns HTTP Status 404 but none helped. They did give me some insight as to what could've been the problem but going through the troubleshooting steps showed me i was on the right path and none of these where problems.

I took a quick glance at this while writing this but i've already tried all that and nothing changed.

this is how my RegisterServlet.java is coded

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {


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



        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");


        // Basic validation
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {

            response.sendRedirect("register.html?error=missingFields");
            return;
        }
        // Hash the password
        String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
        Connection con;
        try {
            // Check if username already exists
           ...

            if (rs.next()) {
                response.sendRedirect("register.html?error=userExists");
                return;
            }

            // Insert user
            ...

            response.sendRedirect(request.getContextPath() + "/login.html");


        } catch (SQLException e) {
            e.printStackTrace();
            response.sendRedirect("register.html?error=dbError");
        }

    }
}

jakarta version 6.0 servlet version 6.1


Solution

  • You can't redirect to JSP if it is under WEB-INF folder. Instead, you can use a request dispatcher to retrieve it from there. For this purpose you should implement doGet() method:

    protected void doGet(HttpServletRequest request,
                              HttpServletResponse response)
                throws ServletException, IOException {
    RequestDispatcher dispatcher = getServletContext()
                    .getRequestDispatcher("/WEB-INF/salesmanDashboard.jsp");
            dispatcher.forward(request, response);        
        }
    
    protected void doPost(HttpServletRequest request,
                              HttpServletResponse response)
                throws ServletException, IOException {
            response.sendRedirect(request.getContextPath() + "/LoginServlet");
        }