Error 404 java servlet

I have an HTML form in a JSP file in my WebContent/jsps folder. I have a servlet class servlet.java in my default package in src folder. In my web.xml it is mapped as /servlet. I have tried several...

Introduction

This can have a lot of causes which are broken down in following sections:

  • Put servlet class in a package
  • Set servlet URL in url-pattern
  • @WebServlet works only on Servlet 3.0 or newer
  • javax.servlet.* doesn’t work anymore in Servlet 5.0 or newer
  • Make sure compiled *.class file is present in built WAR
  • Test the servlet individually without any JSP/HTML page
  • Use domain-relative URL to reference servlet from HTML
  • Use straight quotes in HTML attributes

Put servlet class in a package

First of all, put the servlet class in a Java package. You should always put publicly reuseable Java classes in a package, otherwise they are invisible to classes which are in a package, such as the server itself. This way you eliminate potential environment-specific problems. Packageless servlets work only in specific Tomcat+JDK combinations and this should never be relied upon.

In case of a «plain» IDE project, the class needs to be placed in its package structure inside the «Java Sources» folder, not inside «Web Content» folder, which is for web files such as JSP. Below is an example of the folder structure of a default Eclipse Dynamic Web Project as seen in Navigator view (the «Java Sources» folder is in such project by default represented by src folder):

EclipseProjectName
 |-- src
 |    `-- com
 |         `-- example
 |              `-- YourServlet.java
 |-- WebContent
 |    |-- WEB-INF
 |    |    `-- web.xml
 |    `-- jsps
 |         `-- page.jsp
 :

In case of a Maven project, the class needs to be placed in its package structure inside main/java and thus not main/resources, this is for non-class files and absolutely also not main/webapp, this is for web files. Below is an example of the folder structure of a default Maven webapp project as seen in Eclipse’s Navigator view:

MavenProjectName
 |-- src
 |    `-- main
 |         |-- java
 |         |    `-- com
 |         |         `-- example
 |         |              `-- YourServlet.java
 |         |-- resources
 |         `-- webapp
 |              |-- WEB-INF
 |              |    `-- web.xml
 |              `-- jsps
 |                   `-- page.jsp
 :

Note that the /jsps subfolder is not strictly necessary. You can even do without it and put the JSP file directly in webcontent/webapp root, but I’m just taking over this from your question.

Set servlet URL in url-pattern

The servlet URL is specified as the «URL pattern» of the servlet mapping. It’s absolutely not per definition the classname/filename of the servlet class. The URL pattern is to be specified as value of @WebServlet annotation.

package com.example; // Use a package!

import jakarta.servlet.annotation.WebServlet; // or javax.*
import jakarta.servlet.http.HttpServlet; // or javax.*

@WebServlet("/servlet") // This is the URL of the servlet.
public class YourServlet extends HttpServlet { // Must be public and extend HttpServlet.
    // ...
}

In case you want to support path parameters like /servlet/foo/bar, then use an URL pattern of /servlet/* instead. See also Servlet and path parameters like /xyz/{value}/test, how to map in web.xml?

Do note that it’s considered a bad practice to use a Servlet URL pattern of /* or / in an attempt to have a «front controller». So do not abuse these URL patterns in an attempt to try to catch all URLs. For an in depth explanation see also Difference between / and /* in servlet mapping url pattern.

@WebServlet works only on Servlet 3.0 or newer

In order to use @WebServlet, you only need to make sure that your web.xml file, if any (it’s optional since Servlet 3.0), is declared conform Servlet 3.0+ version and thus not conform e.g. 2.5 version or lower. It should absolutely also not have any <!DOCTYPE> line. Below is a Servlet 6.0 compatible one (which matches Tomcat 10.1+, WildFly 27+ (Preview), GlassFish/Payara 7+, etc) in its entirety:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns="https://jakarta.ee/xml/ns/jakartaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
    version="6.0"
>
    <!-- Config here. -->
</web-app>

And below is a Servlet 5.0 compatible one (which matches Tomcat 10.0.x, WildFly 22+ (Preview), GlassFish/Payara 6+, etc).

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns="https://jakarta.ee/xml/ns/jakartaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
    version="5.0"
>
    <!-- Config here. -->
</web-app>

And below is a Servlet 4.0 compatible one (which matches Tomcat 9+, WildFly 11+, GlassFish/Payara 5+, etc).

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0"
>
    <!-- Config here. -->
</web-app>

Or, in case you’re not on Servlet 3.0+ yet (e.g. Tomcat 6 or older), then remove the @WebServlet annotation.

package com.example;

import javax.servlet.http.HttpServlet;

public class YourServlet extends HttpServlet {
    // ...
}

And register the servlet instead in web.xml like this:

<servlet>
    <servlet-name>yourServlet</servlet-name>
    <servlet-class>com.example.YourServlet</servlet-class> <!-- Including the package thus -->
</servlet>
<servlet-mapping>
    <servlet-name>yourServlet</servlet-name>
    <url-pattern>/servlet</url-pattern>  <!-- This is the URL of the servlet. -->
</servlet-mapping>

Note thus that you should not use both ways. Use either annotation based configuarion or XML based configuration. When you have both, then XML based configuration will override annotation based configuration.

javax.servlet.* doesn’t work anymore in Servlet 5.0 or newer

Since Jakarta EE 9 / Servlet 5.0 (Tomcat 10, TomEE 9, WildFly 22 Preview, GlassFish 6, Payara 6, Liberty 22, etc), the javax.* package has been renamed to jakarta.* package.

In other words, please make absolutely sure that you don’t randomly put JAR files of a different server in your WAR project such as tomcat-servlet-api-9.x.x.jar merely in order to get the javax.* package to compile. This will only cause trouble. Remove it altogether and edit the imports of your servlet class from

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

to

import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.*;

In case you’re using Maven, you can find examples of proper pom.xml declarations for Tomcat 10+, Tomcat 9-, JEE 9+ and JEE 8- in this answer: How to properly configure Jakarta EE libraries in Maven pom.xml for Tomcat? The alternative is to downgrade the server to an older version, e.g. from Tomcat 10 back to Tomcat 9 or older, but this is clearly not the recommended way to go.

Make sure compiled *.class file is present in built WAR

In case you’re using a build tool such as Eclipse and/or Maven, then you need to make absolutely sure that the compiled servlet class file resides in its package structure in /WEB-INF/classes folder of the produced WAR file. In case of package com.example; public class YourServlet, it must be located in /WEB-INF/classes/com/example/YourServlet.class. Otherwise you will face in case of @WebServlet also a 404 error, or in case of <servlet> a HTTP 500 error like below:

HTTP Status 500

Error instantiating servlet class com.example.YourServlet

And find in the server log a java.lang.ClassNotFoundException: com.example.YourServlet, followed by a java.lang.NoClassDefFoundError: com.example.YourServlet, in turn followed by jakarta.servlet.ServletException: Error instantiating servlet class com.example.YourServlet.

An easy way to verify if the servlet is correctly compiled and placed in classpath is to let the build tool produce a WAR file (e.g. rightclick project, Export > WAR file in Eclipse) and then inspect its contents with a ZIP tool. If the servlet class is missing in /WEB-INF/classes, or if the export causes an error, then the project is badly configured or some IDE/project configuration defaults have been mistakenly reverted (e.g. Project > Build Automatically has been disabled in Eclipse).

You also need to make sure that the project icon has no red cross indicating a build error. You can find the exact error in Problems view (Window > Show View > Other…). Usually the error message is fine Googlable. In case you have no clue, best is to restart from scratch and do not touch any IDE/project configuration defaults. In case you’re using Eclipse, you can find instructions in How do I import the javax.servlet / jakarta.servlet API in my Eclipse project?

Test the servlet individually without any JSP/HTML page

Provided that the server runs on localhost:8080, and that the WAR is successfully deployed on a context path of /contextname (which defaults to the IDE project name, case sensitive!), and the servlet hasn’t failed its initialization (read server logs for any deploy/servlet success/fail messages and the actual context path and servlet mapping), then a servlet with URL pattern of /servlet is available at http://localhost:8080/contextname/servlet.

You can just enter it straight in browser’s address bar to test it invidivually. If its doGet() is properly overriden and implemented, then you will see its output in browser. Or if you don’t have any doGet() or if it incorrectly calls super.doGet(), then a «HTTP 405: HTTP method GET is not supported by this URL» error will be shown (which is still better than a 404 as a 405 is evidence that the servlet itself is actually found).

Overriding service() is a bad practice, unless you’re reinventing a MVC framework — which is very unlikely if you’re just starting out with servlets and are clueless as to the problem described in the current question ;) See also Design Patterns web based applications.

Regardless, if the servlet already returns 404 when tested invidivually, then it’s entirely pointless to try with a HTML form instead. Logically, it’s therefore also entirely pointless to include any HTML form in questions about 404 errors from a servlet.

Use domain-relative URL to reference servlet from HTML

Once you’ve verified that the servlet works fine when invoked individually, then you can advance to HTML. As to your concrete problem with the HTML form, the <form action> value needs to be a valid URL. The same applies to <a href>, <img src>, <script src>, etc. You need to understand how absolute/relative URLs work. You know, an URL is a web address as you can enter/see in the webbrowser’s address bar. If you’re specifying a relative URL as form action, i.e. without the http:// scheme, then it becomes relative to the current URL as you see in your webbrowser’s address bar. It’s thus absolutely not relative to the JSP/HTML file location in server’s WAR folder structure as many starters seem to think.

So, assuming that the JSP page with the HTML form is opened by http://localhost:8080/contextname/jsps/page.jsp (and thus not by file://...), and you need to submit to a servlet located in http://localhost:8080/contextname/servlet, here are several cases (note that you can here safely substitute <form action> with <a href>, <img src>, <script src>, etc):

  • Form action submits to an URL with a leading slash.

      <form action="/servlet">
    

    The leading slash / makes the URL relative to the domain, thus the form will submit to

      http://localhost:8080/servlet
    

    But this will likely result in a 404 as it’s in the wrong context.


  • Form action submits to an URL without a leading slash.

      <form action="servlet">
    

    This makes the URL relative to the current folder of the current URL, thus the form will submit to

      http://localhost:8080/contextname/jsps/servlet
    

    But this will likely result in a 404 as it’s in the wrong folder.


  • Form action submits to an URL which goes one folder up.

      <form action="../servlet">
    

    This will go one folder up (exactly like as in local disk file system paths!), thus the form will submit to

      http://localhost:8080/contextname/servlet
    

    This one must work!


  • The canonical approach, however, is to make the URL domain-relative so that you don’t need to fix the URLs once again when you happen to move the JSP files around into another folder.

      <form action="${pageContext.request.contextPath}/servlet">
    

    This will generate

      <form action="/contextname/servlet">
    

    Which will thus always submit to the right URL.


Use straight quotes in HTML attributes

You need to make absolutely sure you’re using straight quotes in HTML attributes like action="..." or action='...' and thus not curly quotes like action=”...” or action=’...’. Curly quotes are not supported in HTML and they will simply become part of the value. Watch out when copy-pasting code snippets from blogs! Some blog engines, notably WordPress, are known to by default use so-called «smart quotes» which thus also corrupts the quotes in code snippets this way. On the other hand, instead of copy-pasting code, try simply typing over the code yourself. Additional advantage of actually getting the code through your brain and fingers is that it will make you to remember and understand the code much better in long term and also make you a better developer.

See also:

  • Our servlets wiki page — Contains some hello world examples
  • How to call servlet class from HTML form
  • doGet and doPost in Servlets
  • How do I pass current item to Java method by clicking a hyperlink or button in JSP page?

Other cases of HTTP Status 404 error:

  • HTTP Status 404 — Servlet [ServletName] is not available
  • HTTP Status 404 — The requested resource (/ProjectName/) is not available
  • HTTP Status 404 — The requested resource (/) is not available
  • JSP in /WEB-INF returns «HTTP Status 404 The requested resource is not available»
  • Referencing a resource placed in WEB-INF folder in JSP file returns HTTP 404 on resource
  • Browser can’t access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

Question

I am trying to run a web application on a Liberty JVM server in my CICS Transaction Server for z/OS (CICS TS) region but I receive the following message(s):

 Error 404: javax.servlet.UnavailableException: 
 SRVE0202E: Servlet [com.ibm.cics.liberty.HelloWorld.Hello]: com.ibm.cics.HelloWorld.Hello
            was found, but is corrupted:
      SRVE0227E: Check that the class resides in the proper package directory. 
      SRVE0228E: Check that the classname has been defined in the server using the proper
                 case and fully qualified package.
      SRVE0229E: Check that the class was transferred to the filesystem using a binary                      transfer mode. 
      SRVE0230E: Check that the class was compiled using the proper case (as defined in the                 class definition). 
      SRVE0231E: Check that the class file was not renamed after it was compiled.

I have tried exporting my CICS Bundle to my zFS again and re-installing the CICS BUNDLE resource definition but I still get this error. What am I doing wrong?

Answer

This Error 404 javax.servlet.UnavailableException indicates that the servlet application was compiled with the wrong version of Java. For example, the servlet was compiled with Java 8 but the Liberty JVM server is running Java 7.1. So you need to check:

  • What version of Java was used to compile the servlet? If you are using the CICS Explorer to create your servlet application, the Explorer comes with its own version of the JRE. However, you can configure the Explorer to use other installed versions of the JRE. You can find the Installed JREs by selecting Window -> Preferences -> Java -> Installed JREs to see what version is being used.

  • What version of Java is the installed JVM server running? In CICS TS, you specify the version of Java to be used by the JVM within the jvmprofile. What is specified in the JAVA_HOME property?

As an example, this error can occur if the HelloWorld servlet was compiled with Java 8 and you are trying to run it on a Liberty JVM server running Java 7.1.
.
So to resolve this, you would either:

  • If you have a Java 7.1 JRE installed on your PC, add it to the Explorer Installed JREs and select it as the JRE to use for compilation, or

  • If you have a Java 8 JRE on your z/OS LPAR, change the JAVA_HOME parameter in the jvmprofile to point to this Java installation.

Shayla Robinson
IBM CICS and CPSM Level2 Support

[{«Business Unit»:{«code»:»BU058″,»label»:»IBM Infrastructure w/TPS»},»Product»:{«code»:»SSGMGV»,»label»:»CICS Transaction Server»},»Platform»:[{«code»:»PF035″,»label»:»z/OS»}],»Component»:»Liberty»,»Version»:»»,»Line of Business»:{«code»:»LOB35″,»label»:»Mainframe SW»}}]

Product Synonym

CICS/TS CICSTS CICS TS CICS Transaction Server

Sample problem:

I have an HTML form in a JSP file in my WebContent/jsps folder. I have a servlet class servlet.java in my default package in src folder. In my web.xml it is mapped as /servlet.

I have tried several URLs in action attribute of the HTML form:

<form action="/servlet">
<form action="/servlet.java">
<form action="/src/servlet.java">
<form action="../servlet.java">

But none of those work. They all keep returning a HTTP 404 error like below in Tomcat 6/7/8:

HTTP Status 404 — /servlet

Description: The requested resource (/servlet) is not available.

Or as below in Tomcat 8.5/9:

HTTP Status 404 — Not Found

Message: /servlet

Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Why is it not working?

Answer #1:

Introduction

This can have a lot of causes which are broken down in following sections:

  • Put servlet class in a package
  • Set servlet URL in url-pattern
  • @WebServlet works only on Servlet 3.0 or newer
  • javax.servlet.* doesn’t work anymore in Servlet 5.0 or newer
  • Make sure compiled *.class file is present in built WAR
  • Test the servlet individually without any JSP/HTML page
  • Use domain-relative URL to reference servlet from HTML
  • Use straight quotes in HTML attributes

Put servlet class in a package

First of all, put the servlet class in a Java package. You should always put publicly reuseable Java classes in a package, otherwise they are invisible to classes which are in a package, such as the server itself. This way you eliminate potential environment-specific problems. Packageless servlets work only in specific Tomcat+JDK combinations and this should never be relied upon.

In case of a “plain” IDE project, the class needs to be placed in its package structure inside the “Java Sources” folder, not inside “Web Content” folder, which is for web files such as JSP. Below is an example of the folder structure of a default Eclipse Dynamic Web Project as seen in Navigator view (the “Java Sources” folder is in such project by default represented by src folder):

EclipseProjectName
 |-- src
 |    `-- com
 |         `-- example
 |              `-- YourServlet.java
 |-- WebContent
 |    |-- WEB-INF
 |    |    `-- web.xml
 |    `-- jsps
 |         `-- page.jsp
 :

In case of a Maven project, the class needs to be placed in its package structure inside main/java and thus not main/resources, this is for non-class files and absolutely also not main/webapp, this is for web files. Below is an example of the folder structure of a default Maven webapp project as seen in Eclipse’s Navigator view:

MavenProjectName
 |-- src
 |    `-- main
 |         |-- java
 |         |    `-- com
 |         |         `-- example
 |         |              `-- YourServlet.java
 |         |-- resources
 |         `-- webapp
 |              |-- WEB-INF
 |              |    `-- web.xml
 |              `-- jsps
 |                   `-- page.jsp
 :

Note that the /jsps subfolder is not strictly necessary. You can even do without it and put the JSP file directly in webcontent/webapp root, but I’m just taking over this from your question.

Set servlet URL in url-pattern

The servlet URL is specified as the “URL pattern” of the servlet mapping. It’s absolutely not per definition the classname/filename of the servlet class. The URL pattern is to be specified as value of @WebServlet annotation.

package com.example; // Use a package!

@WebServlet("/servlet") // This is the URL of the servlet.
public class YourServlet extends HttpServlet { // Must be public and extend HttpServlet.
    // ...
}

In case you want to support path parameters like /servlet/foo/bar, then use an URL pattern of /servlet/* instead. See also Servlet and path parameters like /xyz/{value}/test, how to map in web.xml?

@WebServlet works only on Servlet 3.0 or newer

In order to use @WebServlet, you only need to make sure that your web.xml file, if any (it’s optional since Servlet 3.0), is declared conform Servlet 3.0+ version and thus not conform e.g. 2.5 version or lower. Below is a Servlet 4.0 compatible one (which matches Tomcat 9+, WildFly 11+, Payara 5+, etc).

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0"
>
    <!-- Config here. -->
</web-app>

Or, in case you’re not on Servlet 3.0+ yet (e.g. Tomcat 6 or older), then remove the @WebServlet annotation.

package com.example;

public class YourServlet extends HttpServlet {
    // ...
}

And register the servlet instead in web.xml like this:

<servlet>
    <servlet-name>yourServlet</servlet-name>
    <servlet-class>com.example.YourServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>yourServlet</servlet-name>
    <url-pattern>/servlet</url-pattern>  <!-- This is the URL of the servlet. -->
</servlet-mapping>

Note thus that you should not use both ways. Use either annotation based configuarion or XML based configuration. When you have both, then XML based configuration will override annotation based configuration.

javax.servlet.* doesn’t work anymore in Servlet 5.0 or newer

Since Jakarta EE 9 / Servlet 5.0 (Tomcat 10, TomEE 9, WildFly 22 Preview, GlassFish 6, Payara 6, Liberty 22, etc), the javax.* package has been renamed to jakarta.* package.

In other words, please make absolutely sure that you don’t randomly put JAR files of a different server in your WAR project such as tomcat-servlet-api-9.x.x.jar merely in order to get the javax.* package to compile. This will only cause trouble. Remove it altogether and edit the imports of your servlet class from

import javax.servlet.*;
import javax.servlet.http.*;

to

import jakarta.servlet.*;
import jakarta.servlet.http.*;

In case you’re using Maven, you can find examples of proper pom.xml declarations for Tomcat 10+, Tomcat 9-, JEE 9+ and JEE 8- in this answer: Tomcat casting servlets to javax.servlet.Servlet instead of jakarta.servlet.http.HttpServlet

Make sure compiled *.class file is present in built WAR

In case you’re using a build tool such as Eclipse and/or Maven, then you need to make absolutely sure that the compiled servlet class file resides in its package structure in /WEB-INF/classes folder of the produced WAR file. In case of package com.example; public class YourServlet, it must be located in /WEB-INF/classes/com/example/YourServlet.class. Otherwise you will face in case of @WebServlet also a 404 error, or in case of <servlet> a HTTP 500 error like below:

Error instantiating servlet class com.example.YourServlet

And find in the server log a java.lang.ClassNotFoundException: com.example.YourServlet, followed by a java.lang.NoClassDefFoundError: com.example.YourServlet, in turn followed by javax.servlet.ServletException: Error instantiating servlet class com.example.YourServlet.

An easy way to verify if the servlet is correctly compiled and placed in classpath is to let the build tool produce a WAR file (e.g. rightclick project, Export > WAR file in Eclipse) and then inspect its contents with a ZIP tool. If the servlet class is missing in /WEB-INF/classes, or if the export causes an error, then the project is badly configured or some IDE/project configuration defaults have been mistakenly reverted (e.g. Project > Build Automatically has been disabled in Eclipse).

You also need to make sure that the project icon has no red cross indicating a build error. You can find the exact error in Problems view (Window > Show View > Other…). Usually the error message is fine Googlable. In case you have no clue, best is to restart from scratch and do not touch any IDE/project configuration defaults.

Test the servlet individually without any JSP/HTML page

Provided that the server runs on localhost:8080, and that the WAR is successfully deployed on a context path of /contextname (which defaults to the IDE project name, case sensitive!), and the servlet hasn’t failed its initialization (read server logs for any deploy/servlet success/fail messages and the actual context path and servlet mapping), then a servlet with URL pattern of /servlet is available at http://localhost:8080/contextname/servlet.

You can just enter it straight in browser’s address bar to test it invidivually. If its doGet() is properly overriden and implemented, then you will see its output in browser. Or if you don’t have any doGet() or if it incorrectly calls super.doGet(), then a “HTTP 405: HTTP method GET is not supported by this URL” error will be shown (which is still better than a 404 as a 405 is evidence that the servlet itself is actually found).

Overriding service() is a bad practice, unless you’re reinventing a MVC framework — which is very unlikely if you’re just starting out with servlets and are clueless as to the problem described in the current question 😉

Regardless, if the servlet already returns 404 when tested invidivually, then it’s entirely pointless to try with a HTML form instead. Logically, it’s therefore also entirely pointless to include any HTML form in questions about 404 errors from a servlet.

Use domain-relative URL to reference servlet from HTML

Once you’ve verified that the servlet works fine when invoked individually, then you can advance to HTML. As to your concrete problem with the HTML form, the <form action> value needs to be a valid URL. The same applies to <a href><img src><script src>, etc. You need to understand how absolute/relative URLs work. You know, an URL is a web address as you can enter/see in the webbrowser’s address bar. If you’re specifying a relative URL as form action, i.e. without the http:// scheme, then it becomes relative to the current URL as you see in your webbrowser’s address bar. It’s thus absolutely not relative to the JSP/HTML file location in server’s WAR folder structure as many starters seem to think.

So, assuming that the JSP page with the HTML form is opened by http://localhost:8080/contextname/jsps/page.jsp (and thus not by file://...), and you need to submit to a servlet located in http://localhost:8080/contextname/servlet, here are several cases (note that you can here safely substitute <form action> with <a href><img src><script src>, etc):

  • Form action submits to an URL with a leading slash. <form action="/servlet"> The leading slash / makes the URL relative to the domain, thus the form will submit to http://localhost:8080/servlet But this will likely result in a 404 as it’s in the wrong context.
  • Form action submits to an URL without a leading slash. <form action="servlet"> This makes the URL relative to the current folder of the current URL, thus the form will submit to http://localhost:8080/contextname/jsps/servlet But this will likely result in a 404 as it’s in the wrong folder.
  • Form action submits to an URL which goes one folder up. <form action="../servlet"> This will go one folder up (exactly like as in local disk file system paths!), thus the form will submit to http://localhost:8080/contextname/servlet This one must work!
  • The canonical approach, however, is to make the URL domain-relative so that you don’t need to fix the URLs once again when you happen to move the JSP files around into another folder. <form action="${pageContext.request.contextPath}/servlet"> This will generate <form action="/contextname/servlet"> Which will thus always submit to the right URL.

Use straight quotes in HTML attributes

You need to make absolutely sure you’re using straight quotes in HTML attributes like action="..." or action='...' and thus not curly quotes like action=”...” or action=’...’. Curly quotes are not supported in HTML and they will simply become part of the value. Watch out when copy-pasting code snippets from blogs! Some blog engines, notably WordPress, are known to by default use so-called “smart quotes” which thus also corrupts the quotes in code snippets this way. On the other hand, instead of copy-pasting code, try simply typing over the code yourself. Additional advantage of actually getting the code through your brain and fingers is that it will make you to remember and understand the code much better in long term and also make you a better developer.

Answer #2:

Scenario #1: You accidentially re-deployed from the command line while tomcat was already running.

Short Answer: Stop Tomcat, delete target folder, mvn package, then re-deploy


Scenario #2: request.getRequestDispatcher(“MIS_SPELLED_FILE_NAME.jsp”)

Short Answer: Check file name spelling, make sure case is correct.


Scenario #3: Class Not Found Exceptions (Answer put here because: Question# 17982240 ) (java.lang.ClassNotFoundException for servlet in tomcat with eclipse ) (was marked as duplicate and directed me here )

Short Answer #3.1: web.xml has wrong package path in servlet-class tag.

Short Answer #3.2: java file has wrong import statement.


Below is further details for Scenario #1:


1: Stop Tomcat

  • Option 1: Via CTRL+C in terminal.
  • Option 2: (terminal closed while tomcat still running)
  • ———— 2.1: press:Windows+R –> type:”services.msc
  • ———— 2.2: Find “Apache Tomcat #.# Tomcat#” in Name column of list.
  • ———— 2.3: Right Click –> “stop

2: Delete the “target” folder. (mvn clean will not help you here)

3: mvn package

4: YOUR_DEPLOYMENT_COMMAND_HERE

(Mine: java -jar target/dependency/webapp-runner.jar –port 5190 target/*.war )

Full Back Story:


Accidentially opened a new git-bash window and tried to deploy a .war file for my heroku project via:

java -jar target/dependency/webapp-runner.jar –port 5190 target/*.war

After a failure to deploy, I realized I had two git-bash windows open, and had not used CTLR+C to stop the previous deployment.

I was met with:

HTTP Status 404 – Not Found Type Status Report

Message /if-student-test.jsp

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Apache Tomcat/8.5.31

Below is further details for Scenario #3:


SCENARIO 3.1: The servlet-class package path is wrong in your web.xml file.

It should MATCH the package statement at top of your java servlet class.

File: my_stuff/MyClass.java:

   package my_stuff;

File: PRJ_ROOT/src/main/webapp/WEB-INF/web.xml

   <servlet-class>
   my_stuff.MyClass
   </servlet-class>

SCENARIO 3.2:

You put the wrong “package” statement at top of your myClass.java file.

For example:

File is in: “/my_stuff” folder

You mistakenly write:

package com.my_stuff

This is tricky because:

1: The maven build (mvn package) will not report any errors here.

2: servlet-class line in web.xml can have CORRECT package path. E.g:

<servlet-class>
my_stuff.MyClass
</servlet-class>

Stack Used: Notepad++ + GitBash + Maven + Heroku Web App Runner + Tomcat9 + Windows10:

Answer #3:

Check if you have entered the correct URL Mapping as specified in the Web.xml

For example:

In the web.xml, your servlet declaration maybe:

<servlet>
        <servlet-name>ControllerA</servlet-name>
        <servlet-class>PackageName.ControllerA</servlet-class>
</servlet>

<servlet-mapping>
        <servlet-name>ControllerA</servlet-name>
        <url-pattern>/theController</url-pattern>
</servlet-mapping>

What this snippet does is <url-pattern>/theController</url-pattern>will set the name that will be used to call the servlet from the front end (eg: form) through the URL. Therefore when you reference the servlet in the front end, in order to ensure that the request goes to the servlet “ControllerA”, it should refer the specified URL Pattern “theController” from the form.

eg:

<form action="theController" method="POST">
</form>

Hope you learned something from this post.

Follow Programming Articles for more!

In this tutorial we will tackle servlet 3 exception handling. When a servlet generates an error we can handle those exceptions on various ways, lets say a user tries a URL that does not map to a servlet the user typically gets a 404 page. With the error listing in our web.xml also known as deployment descriptor we can handle those exceptions.

Project structure

+--src
|   +--main
|       +--java
|           +--com
|               +--memorynotfound
|                   |--ErrorServlet.java
|                   |--ExampleServlet.java
|       |--resources
|       +--webapp
|           +--WEB-INF
|               |--web.xml
pom.xml

Maven Dependency

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

Defining our Servlet that will produce an error

This servlet is used to throw an error tot test our configuration.

package com.memorynotfound;

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 java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/error")
public class ExampleServlet extends HttpServlet{

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        throw new UnsupportedOperationException("HTTP GET request is not allowed!");
    }

}

Servlet 3 Exception Handling

We will map this servlet in our servlet descriptor to handle all the exception. You can get information about the exception that occurred from the request attributes. Here is a list of possible attributes that are in the request when an exception occurred.

  • javax.servlet.error.exception will hold information about the exception thrown.
  • javax.servlet.error.status_code will hold the statuscode returned by the container.
  • javax.servlet.error.servlet_name will hold the servlet name in case the exception is thrown from within a servlet.
  • javax.servlet.error.request_uri will hold the request URI from where the error request originated.
package com.memorynotfound;

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 java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/error-handler")
public class ErrorServlet extends HttpServlet{

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // Analyze the servlet exception
        Exception exception = (Exception)req.getAttribute("javax.servlet.error.exception");
        Integer statusCode = (Integer)req.getAttribute("javax.servlet.error.status_code");
        String servletName = (String)req.getAttribute("javax.servlet.error.servlet_name");
        String requestUri = (String)req.getAttribute("javax.servlet.error.request_uri");

        // Set response content type
        resp.setContentType("text/html");

        // print the output
        PrintWriter out = resp.getWriter();
        out.write("<html><head><title>Servlet 3 Exception Handling example</title></head><body>");
        if (statusCode != 500){
            out.write("<h3>Servlet 3 Exception Handling</h3>");
            out.write("<strong>Status Code</strong>:" + statusCode + "<br>");
            out.write("<strong>Requested URI</strong>:" + requestUri);
        } else {
            out.write("<h3>Servlet 3 Exception Handling</h3>");
            out.write("<ul><li>Servlet Name:" + servletName + "</li>");
            out.write("<li>Exception Name:" + exception.getClass().getName() + "</li>");
            out.write("<li>Requested URI:" + requestUri + "</li>");
            out.write("<li>Exception Message:" + exception.getMessage() + "</li>");
            out.write("</ul>");
        }
        out.write("</body></html>");
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}

Servlet 3 web.xml Configuration

We can define our servlet 3 exception handling servlet in the servlet descriptor.

  • Global: If none of the other error-code or exception-type definitions maps then this global location element will map to the exception handler.
  • Error Code: If a specific error occurres that maps to an error code then the error page will be forwarded to the registred servlet 3 exception handling error servlet.
  • Exception Type: This will maps the thrown exception with a exception handler.
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">

    <!-- define global error handler -->
    <error-page>
        <location>/error-handler</location>
    </error-page>

    <!-- define specific error code handler -->
    <error-page>
        <error-code>404</error-code>
        <location>/error-handler</location>
    </error-page>

    <!-- define specific error exception handler -->
    <error-page>
        <exception-type>java.lang.UnsupportedOperationException</exception-type>
        <location>/error-handler</location>
    </error-page>

</web-app>

Demo

404 – Page Not Found

URL: http://localhost:8080/exception-handling/page-does-not-exist

404 servlet 3 exception handling example

500 – Servlet That Generates an Error

URL: http://localhost:8080/exception-handling/error

500 servlet 3 exception handling example

References

  • Servlet 3 API specification

Download

Обработка ошибок

Последнее обновление: 17.09.2018

Файл web.xml позволяет указать, какие страницы html или jsp будут отправляться пользователю при отправке статусных кодов ошибок.
Для этого в web.xml применяется элемент <error-page>.

Внутри этого элемента с помощью элемента <error-code> указывается
статусный код ошибки, который надо обработать. А элемент <location> указывает на путь к
странице html или jsp, которая будет отправляться пользователю.

Например, добавим в проект в папку WebContent новый файл 404.html со следующим кодом:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Not Found</title>
</head>
<body>
<h2>Resource not found!</h2>
</body>
</html>

error page in Java EE

В файле web.xml определим следующее содержимое:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0">
  <error-page>
  	<error-code>404</error-code>
  	<location>/404.html</location>
  </error-page>
</web-app>

В данном случае элемент error-code указывает, что мы будем обрабатывать ошибки со статусным кодом 404 (то есть такие ошибки,
которые подразумевают отсутствие ресурса на сервере). А элемент location указывает, что в случае обращения к несуществующему ресурсу
пользователю будет отправляться страница 404.html.

errors in web.xml in Java EE

Обработка исключений

Кроме настройки обработки стандартных ошибок протокола http,типа 404 или 403, файл web.xml позволяет настроить обработку исключений,
которые могут возникнуть при обработке запроса. Для этого в web.xml применяется элемент <exception-type.

Например, добавим в проект в папку WebContent новый файл error.jsp и определим
в нем следующий код:

<%
   String message = pageContext.getException().getMessage();
   String exception = pageContext.getException().getClass().toString();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Exception</title>
</head>
<body>
<h2>Exception occurred while processing the request</h2>
<p>Type: <%= exception%></p>
<p>Message: <%= message %></p>
</body>
</html>

Данная страница jsp будет отображать информацию об исключении. Через глобальный объект pageContext в страницу передается контекст.
Если при обработке запроса возникло какое-нибудь исключение, то метод pageContext.getException() возвратит это исключение в
виде объекта Exception. И далее мы можем исследовать этот объект и вызывать его методы, например, получить тип исключения и сообщение об исключении.

Симитируем с сервлете какое-нибудь исключение:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    		throws ServletException, IOException {
    	
    	int x = 0;
    	int y = 8 / x;
    }
}

В данном случае мы получаем ошибку деления на нуль, которая представлена типом java.lang.ArithmeticException.

Теперь определим следующий файл web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0">
  <error-page>
  	<exception-type>java.lang.Throwable</exception-type>
  	<location>/error.jsp</location>
  </error-page>
</web-app>

Элемент exception-type указывает, что обрабатываться будут исключения типа java.lang.Throwable. Поскольку это базовый класс для всех типов исключений,
то фактически мы будем обрабатывать все исключения. Хотя можно конкретизировать тип исключения, например, указать тот же java.lang.ArithmeticException.

Элемент location определяет страницу, которая отправляется пользователю при возникновении исключении. В данном случае это
error.jsp.

В итоге при обращении к сервлету будет сгенерировано исключение, и мы увидим информацию о нем:

Exception type in web.xml in Java EE

Содержание

  1. [Solved] Tomcat Error HTTP Status 404 Not Found
  2. Other Java Servlet Tutorials:
  3. About the Author:
  4. Servlet returns “HTTP Status 404 The requested resource (/servlet) is not available” [Answered]
  5. Sample problem:
  6. HTTP Status 404 — /servlet
  7. HTTP Status 404 — Not Found
  8. Answer #1:
  9. Introduction
  10. Put servlet class in a package
  11. Set servlet URL in url-pattern
  12. @WebServlet works only on Servlet 3.0 or newer
  13. javax.servlet.* doesn’t work anymore in Servlet 5.0 or newer
  14. Make sure compiled *.class file is present in built WAR
  15. HTTP Status 500
  16. Test the servlet individually without any JSP/HTML page
  17. Use domain-relative URL to reference servlet from HTML

[Solved] Tomcat Error HTTP Status 404 Not Found

The error code is HTTP 404 (not found) and the description is:

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

This error means the server could not find the requested resource (JSP, HTML, images…) and returns HTTP status code 404. Most of the time, you can fix this error by correcting the URL. However, sometimes it’s not easy like that, making it is an annoying error.

Here I suggest some possible reasons and how to fix the error HTTP 404 in Java web development with Tomcat.

1. The URL is not handled by any Java servlets

You need to check URL mapping in your servlet classes to make sure the requested URL is actually handled by a servlet. For example:

This servlet handles the URL /view_book . If the request URL is /view_books the server will raise HTTP 404 error. You can fix by either correcting the URL or correcting the URL mapping in the @WebServlet annotation.

2. Java servlet forwarding to a resource that does not exist

In this case, the requested URL is handled by a Java servlet, but code in the servlet forwards to a resource (JSP, HTML…) which does not exist, as shown in the following screenshot:

The code in the servlet class would look like this:

You can fix by correcting the forward path in the servlet, and make sure that the forwarded resource does actually exist in the given path.

3. URL is case-sensitive

Note that Tomcat treats URL as case-sensitive, for instance /Register is different than /register . So you need to check and use correct case for the letters in request URL.

Also pay attention to the webapp name in the URL, for instance http://localhost:8080/BookstoreWebsite/ is different than http://localhost:8080/BookStoreWebsite/

TIP: in Eclipse, you can right click on the project, then click Run As > Run on Server, the IDE will always use the correct name of the web application.

Finally, you should not let the user see the raw HTTP 404 error page rendered by the server. Instead, you should design your own user-friendly 404 error page – follow this tutorial: How to Handle Error for Java web applications.

You can also watch the video version below:

Other Java Servlet Tutorials:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Servlet returns “HTTP Status 404 The requested resource (/servlet) is not available” [Answered]

Sample problem:

I have an HTML form in a JSP file in my WebContent/jsps folder. I have a servlet class servlet.java in my default package in src folder. In my web.xml it is mapped as /servlet .

I have tried several URLs in action attribute of the HTML form:

But none of those work. They all keep returning a HTTP 404 error like below in Tomcat 6/7/8:

HTTP Status 404 — /servlet

Description: The requested resource (/servlet) is not available.

Or as below in Tomcat 8.5/9:

HTTP Status 404 — Not Found

Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Why is it not working?

Answer #1:

Introduction

This can have a lot of causes which are broken down in following sections:

  • Put servlet class in a package
  • Set servlet URL in url-pattern
  • @WebServlet works only on Servlet 3.0 or newer
  • javax.servlet.* doesn’t work anymore in Servlet 5.0 or newer
  • Make sure compiled *.class file is present in built WAR
  • Test the servlet individually without any JSP/HTML page
  • Use domain-relative URL to reference servlet from HTML
  • Use straight quotes in HTML attributes

Put servlet class in a package

First of all, put the servlet class in a Java package . You should always put publicly reuseable Java classes in a package, otherwise they are invisible to classes which are in a package, such as the server itself. This way you eliminate potential environment-specific problems. Packageless servlets work only in specific Tomcat+JDK combinations and this should never be relied upon.

In case of a “plain” IDE project, the class needs to be placed in its package structure inside the “Java Sources” folder, not inside “Web Content” folder, which is for web files such as JSP. Below is an example of the folder structure of a default Eclipse Dynamic Web Project as seen in Navigator view (the “Java Sources” folder is in such project by default represented by src folder):

In case of a Maven project, the class needs to be placed in its package structure inside main/java and thus not main/resources , this is for non-class files and absolutely also not main/webapp , this is for web files. Below is an example of the folder structure of a default Maven webapp project as seen in Eclipse’s Navigator view:

Note that the /jsps subfolder is not strictly necessary. You can even do without it and put the JSP file directly in webcontent/webapp root, but I’m just taking over this from your question.

Set servlet URL in url-pattern

The servlet URL is specified as the “URL pattern” of the servlet mapping. It’s absolutely not per definition the classname/filename of the servlet class. The URL pattern is to be specified as value of @WebServlet annotation.

In case you want to support path parameters like /servlet/foo/bar , then use an URL pattern of /servlet/* instead. See also Servlet and path parameters like /xyz//test, how to map in web.xml?

@WebServlet works only on Servlet 3.0 or newer

In order to use @WebServlet , you only need to make sure that your web.xml file, if any (it’s optional since Servlet 3.0), is declared conform Servlet 3.0+ version and thus not conform e.g. 2.5 version or lower. Below is a Servlet 4.0 compatible one (which matches Tomcat 9+, WildFly 11+, Payara 5+, etc).

Or, in case you’re not on Servlet 3.0+ yet (e.g. Tomcat 6 or older), then remove the @WebServlet annotation.

And register the servlet instead in web.xml like this:

Note thus that you should not use both ways. Use either annotation based configuarion or XML based configuration. When you have both, then XML based configuration will override annotation based configuration.

javax.servlet.* doesn’t work anymore in Servlet 5.0 or newer

Since Jakarta EE 9 / Servlet 5.0 (Tomcat 10, TomEE 9, WildFly 22 Preview, GlassFish 6, Payara 6, Liberty 22, etc), the javax.* package has been renamed to jakarta.* package.

In other words, please make absolutely sure that you don’t randomly put JAR files of a different server in your WAR project such as tomcat-servlet-api-9.x.x.jar merely in order to get the javax.* package to compile. This will only cause trouble. Remove it altogether and edit the imports of your servlet class from

In case you’re using Maven, you can find examples of proper pom.xml declarations for Tomcat 10+, Tomcat 9-, JEE 9+ and JEE 8- in this answer: Tomcat casting servlets to javax.servlet.Servlet instead of jakarta.servlet.http.HttpServlet

Make sure compiled *.class file is present in built WAR

In case you’re using a build tool such as Eclipse and/or Maven, then you need to make absolutely sure that the compiled servlet class file resides in its package structure in /WEB-INF/classes folder of the produced WAR file. In case of package com.example; public class YourServlet , it must be located in /WEB-INF/classes/com/example/YourServlet.class . Otherwise you will face in case of @WebServlet also a 404 error, or in case of a HTTP 500 error like below:

HTTP Status 500

Error instantiating servlet class com.example.YourServlet

And find in the server log a java.lang.ClassNotFoundException: com.example.YourServlet , followed by a java.lang.NoClassDefFoundError: com.example.YourServlet , in turn followed by javax.servlet.ServletException: Error instantiating servlet class com.example.YourServlet .

An easy way to verify if the servlet is correctly compiled and placed in classpath is to let the build tool produce a WAR file (e.g. rightclick project, Export > WAR file in Eclipse) and then inspect its contents with a ZIP tool. If the servlet class is missing in /WEB-INF/classes , or if the export causes an error, then the project is badly configured or some IDE/project configuration defaults have been mistakenly reverted (e.g. Project > Build Automatically has been disabled in Eclipse).

You also need to make sure that the project icon has no red cross indicating a build error. You can find the exact error in Problems view (Window > Show View > Other…). Usually the error message is fine Googlable. In case you have no clue, best is to restart from scratch and do not touch any IDE/project configuration defaults.

Test the servlet individually without any JSP/HTML page

Provided that the server runs on localhost:8080 , and that the WAR is successfully deployed on a context path of /contextname (which defaults to the IDE project name, case sensitive!), and the servlet hasn’t failed its initialization (read server logs for any deploy/servlet success/fail messages and the actual context path and servlet mapping), then a servlet with URL pattern of /servlet is available at http://localhost:8080/contextname/servlet .

You can just enter it straight in browser’s address bar to test it invidivually. If its doGet() is properly overriden and implemented, then you will see its output in browser. Or if you don’t have any doGet() or if it incorrectly calls super.doGet() , then a “HTTP 405: HTTP method GET is not supported by this URL” error will be shown (which is still better than a 404 as a 405 is evidence that the servlet itself is actually found).

Overriding service() is a bad practice, unless you’re reinventing a MVC framework — which is very unlikely if you’re just starting out with servlets and are clueless as to the problem described in the current question 😉

Regardless, if the servlet already returns 404 when tested invidivually, then it’s entirely pointless to try with a HTML form instead. Logically, it’s therefore also entirely pointless to include any HTML form in questions about 404 errors from a servlet.

Use domain-relative URL to reference servlet from HTML

Once you’ve verified that the servlet works fine when invoked individually, then you can advance to HTML. As to your concrete problem with the HTML form, the value needs to be a valid URL. The same applies to , ,

Источник

What is 404 Not Found Errror?

It is status code of the execution of a Servlet or Web application. More clear in the next explanation.

User clicks over a hyperlink, some Servlet is called, executed and the response is sent to the user. Sometimes, the mouse click on the hyperlink calls such an attribute of <ACTION> tag which does not exist on the Web server. That is, the source corresponding to the hyperlink does not exist on the Server. Then what server should do to reply to the user?

Server delivers a message to the client, «404 Not Found«. 404 indicates status code of the response. It is a very commonly occurring status code.

404 Not Found indicates:

The source (which can generate the response like a Servlet) requested by the client does not exist on the Server; that is, server is unable to locate the source. Here, client is authorized to access.

Causes of 404 Not Found Error and Fixing it?

  1. The hyperlink (URL) may be broken with some extra spaces not required while it is being typed by the user.
  2. The hyperlink may be a dead hyperlink (which existed earlier but not now).
  3. The source (URL) must have moved to another server temporarily or permanently and server is unable to redirect to the new location.
  4. The extension for an HTML file may be .htm or .html. Should be checked how the server accepts.
    1. For student learning Servlets

    2. Check the spelling of <url-pattern> alias name of Servlet you have typed in the URL (of <ACTION> attrubute of <FORM> tag).
    3. Check you have placed .java file of .class file of the Servlet in the Server.
    4. Check where you have placed .class file and it must be classes folder of Tomcat.
    5. When you correct all, restart the Tomcat and check again.

Know also What is Status code in HTTP Servlets?.

Понравилась статья? Поделить с друзьями:
  • Error 404 html code
  • Error 404 herobrine
  • Error 404 hen
  • Error 404 hatsune miku
  • Error 404 google sites