Weblogic 12.2.1 validation.xml parsing error - bean-validation

I have an ear file that has a validation.xml file in one of its ejb modules when I want to deploy it on Weblogic 12.2.1, then the Weblogic throws the following exception:
<BEA-000000> <Error parsing validation.xml synchronously
java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(File.java:418)
at org.eclipse.persistence.jaxb.ValidationXMLReader.parseValidationXML(ValidationXMLReader.java:147)
at org.eclipse.persistence.jaxb.ValidationXMLReader.call(ValidationXMLReader.java:67)
at org.eclipse.persistence.jaxb.BeanValidationHelper.parseValidationXml(BeanValidationHelper.java:178)
at org.eclipse.persistence.jaxb.BeanValidationHelper.getConstraintsMap(BeanValidationHelper.java:143)
at org.eclipse.persistence.jaxb.BeanValidationHelper.isConstrained(BeanValidationHelper.java:120)
at org.eclipse.persistence.jaxb.JAXBBeanValidator.isConstrainedObject(JAXBBeanValidator.java:255)
at org.eclipse.persistence.jaxb.JAXBBeanValidator.shouldValidate(JAXBBeanValidator.java:206)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.validateAndBuildJAXBElement(JAXBUnmarshaller.java:235)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:640)
at org.hibernate.validator.internal.util.privilegedactions.Unmarshal.run(Unmarshal.java:38)
at org.hibernate.validator.internal.util.privilegedactions.Unmarshal.run(Unmarshal.java:20)
at org.hibernate.validator.internal.xml.ValidationXmlParser.run(ValidationXmlParser.java:201)
at org.hibernate.validator.internal.xml.ValidationXmlParser.unmarshal(ValidationXmlParser.java:125)
at org.hibernate.validator.internal.xml.ValidationXmlParser.parseValidationXml(ValidationXmlParser.java:81)
at org.hibernate.validator.internal.engine.ConfigurationImpl.getBootstrapConfiguration(ConfigurationImpl.java:353)
at org.hibernate.validator.internal.cdi.ValidationExtension.<init>(ValidationExtension.java:120)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.jboss.weld.util.ServiceLoader.prepareInstance(ServiceLoader.java:240)
at org.jboss.weld.util.ServiceLoader.loadService(ServiceLoader.java:214)
at org.jboss.weld.util.ServiceLoader.loadServiceFile(ServiceLoader.java:182)
at org.jboss.weld.util.ServiceLoader.reload(ServiceLoader.java:162)
at org.jboss.weld.util.ServiceLoader.iterator(ServiceLoader.java:297)
at com.oracle.injection.provider.weld.BasicDeployment.getExtensions(BasicDeployment.java:106)
at com.oracle.injection.provider.weld.WeldInjectionContainer.initialize(WeldInjectionContainer.java:92)
at com.oracle.injection.integration.CDIAppDeploymentExtension.initCdi(CDIAppDeploymentExtension.java:64)
at com.oracle.injection.integration.CDIAppDeploymentExtension.activate(CDIAppDeploymentExtension.java:41)
at weblogic.application.internal.flow.AppDeploymentExtensionFlow.activate(AppDeploymentExtensionFlow.java:39)
at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:753)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:263)
at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:67)
at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:601)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:171)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:121)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:343)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:895)
at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1422)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:454)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:181)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:643)
at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:617)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:397)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
The validation.xml file's content shows in the below:
<?xml version="1.0" encoding="UTF-8" ?>
<validation-config
xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://jboss.org/xml/ns/javax/validation/configuration
validation-configuration-1.1.xsd"
version="1.1">
</validation-config>
How to deploy ear file with validation.xml on weblogic 12.2.1?

It drives me crazy too. I tried to downgrade bean validation to 1.0, but did not help.
Here they suggest to ignore it since it is warning only, set the logger to SEVERE level.

I had the same problem with web application.
In my case validation.xml was in one of my jars. I was able to fix the problem by moving the file directly to the war that was being deployed.
In case of ear file I believe the same solution should work.

I think this is a bug in EclipseLink/TopLink (which is used for JPA and JAXB binding in WLS 12.2.1 and upwards). I opened a FORUM entry in the EclipseLink forum: https://www.eclipse.org/forums/index.php/m/1759047/#msg_1759047
Summary: They try to read the validation.xml resource like this:
URL validationXml = Thread.currentThread().getContextClassLoader().getResource("META INF/validation.xml");
and then:
new File(validationXml.toURI())
but the toURI contains an URI that looks like this:
The URL.toString is: zip:/local/saladin/wls12/weblogic/12.2.1.0.0/domains/XXXX/servers/AdminServer/tmp/_WL_user/xxxx-application_1.5.5_dev-SNAPSHOT/s86txs/lib/xxx-xxxx-xxxxdatamodel-1.5.5_dev-SNAPSHOT.jar!/META-INF/validation.xml
So this is not a file, and therefore it cannot work.
The correct way would be to get the resource as Stream and not as File. But as to a solution, I don't know really how to fix it without modifying the EclipseLink source code. It is quite ugly to have those Warnings in the logfile and not being able to do anything about it.

Related

StackOverflowError during Liberty startup during ApplicationStateManager.fireStarting

BLUF: I'm getting a stackoverflow starting my Liberty server with a single war file before it reaches any of my code. I can't debug what is causing the problem. I tried adding trace statements to server.xml but never got files I could interpret (were binary) and trying to Open Log Files had no choices available (greyed out). If anyone has any ideas how to determine what is causing the stack overflow I'd appreciate the help. Thanks in advance. My code does use #Inject but I don't think this is the issue as all works fine if I move code from a separate project/jar into the war project.
Running wlp 17.0.0.1 when starting a single war using shared libraries to jar files in a single directory, I get a StackOverflowError before any of my code is reached (based on setting breakpoints in the RestServicesApplication and any static initializers).
This problem only occurs when some classes have been moved to a separate project and therefore into a separate jar (e.g., moving them back to the war project allows all to run fine).
I've checked that all classes and methods references are public. I'm calling public static methods in the new jar file.
I'm not sure how to figure out the problem as no references to my code are in the ffdc files in the stack traces.
I've verified the needed classes are in the jar file and there are no duplicate classes being referenced.
Essentially, the class in the war file has a call like:
public static JSONObject processFuzzyMatch(ID session,
ID userID, JSONObject request)
throws ILDException {
try {
return NLUFuzzyEntityMatcherFunction.processFuzzyMatch(request);
} catch (Exception e) {
throw new ILDException(e);
}
}
and NLUFuzzyEntityMatcherFunction is in the jar file declared as:
public static JSONObject processFuzzyMatch(JSONObject request)
throws Exception
Here is an example of the reported problem with the last line repeating (for the stack overflow...)
Stack Dump = com.ibm.ws.container.service.state.StateChangeException: java.lang.StackOverflowError
at com.ibm.ws.container.service.state.internal.ApplicationStateManager.fireStarting(ApplicationStateManager.java:33)
at com.ibm.ws.container.service.state.internal.StateChangeServiceImpl.fireApplicationStarting(StateChangeServiceImpl.java:51)
at com.ibm.ws.app.manager.module.internal.DeployedAppInfoBase.preDeployApp(DeployedAppInfoBase.java:376)
at com.ibm.ws.app.manager.module.internal.DeployedAppInfoBase.deployApp(DeployedAppInfoBase.java:403)
at com.ibm.ws.app.manager.war.internal.WARApplicationHandlerImpl.install(WARApplicationHandlerImpl.java:66)
at com.ibm.ws.app.manager.internal.statemachine.StartAction.execute(StartAction.java:141)
at com.ibm.ws.app.manager.internal.statemachine.ApplicationStateMachineImpl.enterState(ApplicationStateMachineImpl.java:1253)
at com.ibm.ws.app.manager.internal.statemachine.ApplicationStateMachineImpl.run(ApplicationStateMachineImpl.java:866)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.StackOverflowError
at java.io.UnixFileSystem.getBooleanAttributes0(Native Method)
at java.io.UnixFileSystem.getBooleanAttributes(UnixFileSystem.java:242)
at java.io.File.exists(File.java:819)
at com.ibm.wsspi.kernel.service.utils.FileUtils$3.run(FileUtils.java:88)
at com.ibm.wsspi.kernel.service.utils.FileUtils$3.run(FileUtils.java:85)
at java.security.AccessController.doPrivileged(Native Method)
at com.ibm.wsspi.kernel.service.utils.FileUtils.fileExists(FileUtils.java:85)
at com.ibm.ws.artifact.loose.internal.LooseArchive$DirEntryInfo.matches(LooseArchive.java:232)
at com.ibm.ws.artifact.loose.internal.LooseArchive$DirEntryInfo.matches(LooseArchive.java:207)
at com.ibm.ws.artifact.loose.internal.LooseArchive.getEntry(LooseArchive.java:782)
at com.ibm.ws.artifact.overlay.internal.DirectoryBasedOverlayContainerImpl.getEntry(DirectoryBasedOverlayContainerImpl.java:838)
at com.ibm.ws.adaptable.module.internal.AdaptableContainerImpl.getEntry(AdaptableContainerImpl.java:113)
at com.ibm.ws.jsp.taglib.TagLibraryCache.loadWebInfMap(TagLibraryCache.java:613)
at com.ibm.ws.jsp.taglib.TagLibraryCache.loadWebInfMap(TagLibraryCache.java:629)
at com.ibm.ws.jsp.taglib.TagLibraryCache.loadWebInfMap(TagLibraryCache.java:629)
(above line repeats due to stack overflow)
This is a known problem on Liberty. The fix to that problem will be available on Liberty 17.0.0.3.
You can use some workarounds:
I assume you have a folder named WEB-INF within a jar. Change the folder name to something else. That folder name causes the JSP engine to go to the web module's WEB-INF (scanning everything again!), instead of the jar's WEB-INF.
Try setting the JSP configuration parameter disableTldSearch to true; this may be troublesome if you are using custom tag libraries. With the property set, all your custom TLD files need to be declared in the web.xml.
Disable CDI; I know this may not be possible for you as you mentioned you are using injections.
Somehow I screwed up the project settings for the jar project (likely because I'd copied the pom.xml from the Web project and forgot to change it to jar...). This may have resulted in the screwed up xml file in the /apps folder with an embedded reference to a non-existent war file (see below):
<?xml version="1.0" encoding="UTF-8"?>
<archive>
<archive targetInArchive="/WEB-INF/lib/ildMicroServices-1.0.0-SNAPSHOT.jar">
<dir sourceOnDisk="/csnext/ild/ild_framework/ildMicroServices/WebContent" targetInArchive="/"/>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildMicroServices/target/classes" targetInArchive="/WEB-INF/classes"/>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildMicroServices/target/test-
classes" targetInArchive="/WEB-INF/classes"/>
</archive>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildRESTServices/target/m2e-wtp/web-resources" targetInArchive="/"/>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildRESTServices/WebContent" targetInArchive="/"/>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildRESTServices/target/classes" targetInArchive="/WEB-INF/classes"/>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildRESTServices/target/test-classes" targetInArchive="/WEB-INF/classes"/>
</archive>
By deleting this embedded archive the problem went away.
I only found this after upgrading from Neon to Oxygen, and 17.0.0.1 to 17.0.0.2 and when setting up the new server using the old server's artifacts, I noticed the xml file in /apps didn't look correct.
I hope this helps somebody.

Servlet returns “HTTP Status 404 The requested resource is not available” in netbeans [duplicate]

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
Or as below in Tomcat 10:
HTTP Status 404 — Not Found
Type: Status Report
Message: The requested resource (/servlet) is not available
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?
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
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:
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>
If you're using IntelliJ, this is what fixed it for me:
Go to the Tomcat configuration:
Configuration > Deployment Tab
Scroll down and add / to the Application Context dropdown
Solution for HTTP Status 404 in NetBeans IDE:
Right click on your project and go to your project properties, then click on run, then input your project relative URL like index.jsp.
Project->Properties
Click on Run
Relative URL:/index.jsp (Select your project root URL)
My issue was that my method was missing the #RequestBody annotation. After adding the annotation I no longer received the 404 exception.
Do the following two steps. I hope, it will solve the "404 not found" issue in tomcat server during the development of java servlet application.
Step 1: Right click on the server(in the server explorer tab)->Properties->Switch Location from workspace metadata to tomcat server
Step 2: Double Click on the server(in the server explorer tab)->Select Use tomcat installation option inside server location menu
I removed the old web library such that are spring framework libraries. And build a new path of the libraries. Then it works.
An old thread, but since I didn't find it elsewhere, here is one more possibility:
If you're using servlet-api 3.0+, then your web.xml must NOT include metadata-complete="true" attribute
This tells tomcat to map the servlets using data given in web.xml instead of using the #WebServlet annotation.
First of all, run your IDE as Admin. After that, right click the project folder -> Project Facets and make sure that the Java Version is set correct. On my PC. (For Example 1.8) Now it should work.
Don't just start your server, for example Wildfly, using the cmd. It has to be launched within the IDE and now visit your localhost URL. Example: http://localhost:8080/HelloWorldServlet/HelloWorld
The fix that worked for me is(if you are using Maven): Rightclick your project, Maven -> Update project. This might give you some other error with the JDK and other Libraries(in my case, MySQL connector), but once you fix them, your original problem should be fixed!
If you would like to open a servlet with javascript without using 'form' and 'submit' button, here is the following code:
var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});
Key:
1) button-id : The 'id' tag you give to your button in your html/jsp file.
2) full-servlet-path: The path that shows in the browser when you run the servlet alone
Mapping in web.xml is what i have done :-
If there's another package made for new program then we must mention :-
packagename.filename between opening and closing of servlet-class tag in xml file.
If you are mapping your files in xml and they are not working or showing errors , then comment on the annotation line of code in the respective files.
Both methods dont work with one another , so either i use annotation method of files mentioned when we create servlet or the way of mapping , then i delete or comment the annotation line. Eg:
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>performance.FirstServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/FirstServ</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>performance.SecondServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/SecondServ</url-pattern>
</servlet-mapping>
Commenting the annotation line of code in the respective file,if mapping in xml is done.
//#WebServlet("/FirstServ")
//#WebServlet("/SecondServ")
If someone is here who is using MySQL and felt that the code was working the previous day and now it doesn't, then I guess you must open MySQL CLI or MySQL Workbench and just make the connection to the database once. Once it gets connected, then the database also gets connected to the Java Application. I used to get the Hibernate Dialect error stating something wrong with com.mysql.jdbc.Driver. I think MySQL in some computers has a startup problem. This solved for me.
If you are a student and new to Java there might be some issue going on with your web.xml file.
Try removing the web.xml file.
Secondly check that your path variables are properly set or not.
Restart tomcat server Or your PC.
Your problem will be surely solved.
I was facing this issue too, I was receiving a 404 when accessing a URL pattern that I knew was linked to a Servlet. The reason is because I had 2 Servlets with their #WebServlet name parameter set as the same string.
#WebServlet(name = "ServletName", urlPatterns = {"/path"})
public class ServletName extends HttpServlet {}
#WebServlet(name = "ServletName", urlPatterns = {"/other-path"})
public class OtherServletName extends HttpServlet {}
Both of the name parameters are the same. If you're using the name parameter, make sure they are unique compared to all other Servlets on your application.
I had the same issue. Tried all of this but didn't help. I managed to solve this issue by adding element tags to beginning and end of the xml file. ill leave my xml file below for reference.
<?xml version="1.0" encoding="UTF-8"?>
<element>
<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">
<servlet>
<servlet-name>InsertServlet</servlet-name>
<servlet-class>com.worklog.InsertServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertServlet</servlet-name>
<url-pattern>/insert</url-pattern>
</servlet-mapping>
</web-app>
</element>
I was having the same issue. I was developing a mvc based REST API where there was no explicit html configuration or files. The API was using Swagger to generate a user interface. The problem started when I introduced Swagger version "3.0.0". I reverted back to Swagger "2.9.2" This solved my problem.
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
Please check context root cannot be empty.
If you're using eclipse:
right click, select properties, then web project settings. Check the context root cannot be empty

HTTP Status 404 - /FirstServlet/MyServlet [duplicate]

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
Or as below in Tomcat 10:
HTTP Status 404 — Not Found
Type: Status Report
Message: The requested resource (/servlet) is not available
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?
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
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:
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>
If you're using IntelliJ, this is what fixed it for me:
Go to the Tomcat configuration:
Configuration > Deployment Tab
Scroll down and add / to the Application Context dropdown
Solution for HTTP Status 404 in NetBeans IDE:
Right click on your project and go to your project properties, then click on run, then input your project relative URL like index.jsp.
Project->Properties
Click on Run
Relative URL:/index.jsp (Select your project root URL)
My issue was that my method was missing the #RequestBody annotation. After adding the annotation I no longer received the 404 exception.
Do the following two steps. I hope, it will solve the "404 not found" issue in tomcat server during the development of java servlet application.
Step 1: Right click on the server(in the server explorer tab)->Properties->Switch Location from workspace metadata to tomcat server
Step 2: Double Click on the server(in the server explorer tab)->Select Use tomcat installation option inside server location menu
I removed the old web library such that are spring framework libraries. And build a new path of the libraries. Then it works.
An old thread, but since I didn't find it elsewhere, here is one more possibility:
If you're using servlet-api 3.0+, then your web.xml must NOT include metadata-complete="true" attribute
This tells tomcat to map the servlets using data given in web.xml instead of using the #WebServlet annotation.
First of all, run your IDE as Admin. After that, right click the project folder -> Project Facets and make sure that the Java Version is set correct. On my PC. (For Example 1.8) Now it should work.
Don't just start your server, for example Wildfly, using the cmd. It has to be launched within the IDE and now visit your localhost URL. Example: http://localhost:8080/HelloWorldServlet/HelloWorld
The fix that worked for me is(if you are using Maven): Rightclick your project, Maven -> Update project. This might give you some other error with the JDK and other Libraries(in my case, MySQL connector), but once you fix them, your original problem should be fixed!
If you would like to open a servlet with javascript without using 'form' and 'submit' button, here is the following code:
var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});
Key:
1) button-id : The 'id' tag you give to your button in your html/jsp file.
2) full-servlet-path: The path that shows in the browser when you run the servlet alone
Mapping in web.xml is what i have done :-
If there's another package made for new program then we must mention :-
packagename.filename between opening and closing of servlet-class tag in xml file.
If you are mapping your files in xml and they are not working or showing errors , then comment on the annotation line of code in the respective files.
Both methods dont work with one another , so either i use annotation method of files mentioned when we create servlet or the way of mapping , then i delete or comment the annotation line. Eg:
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>performance.FirstServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/FirstServ</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>performance.SecondServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/SecondServ</url-pattern>
</servlet-mapping>
Commenting the annotation line of code in the respective file,if mapping in xml is done.
//#WebServlet("/FirstServ")
//#WebServlet("/SecondServ")
If someone is here who is using MySQL and felt that the code was working the previous day and now it doesn't, then I guess you must open MySQL CLI or MySQL Workbench and just make the connection to the database once. Once it gets connected, then the database also gets connected to the Java Application. I used to get the Hibernate Dialect error stating something wrong with com.mysql.jdbc.Driver. I think MySQL in some computers has a startup problem. This solved for me.
If you are a student and new to Java there might be some issue going on with your web.xml file.
Try removing the web.xml file.
Secondly check that your path variables are properly set or not.
Restart tomcat server Or your PC.
Your problem will be surely solved.
I was facing this issue too, I was receiving a 404 when accessing a URL pattern that I knew was linked to a Servlet. The reason is because I had 2 Servlets with their #WebServlet name parameter set as the same string.
#WebServlet(name = "ServletName", urlPatterns = {"/path"})
public class ServletName extends HttpServlet {}
#WebServlet(name = "ServletName", urlPatterns = {"/other-path"})
public class OtherServletName extends HttpServlet {}
Both of the name parameters are the same. If you're using the name parameter, make sure they are unique compared to all other Servlets on your application.
I had the same issue. Tried all of this but didn't help. I managed to solve this issue by adding element tags to beginning and end of the xml file. ill leave my xml file below for reference.
<?xml version="1.0" encoding="UTF-8"?>
<element>
<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">
<servlet>
<servlet-name>InsertServlet</servlet-name>
<servlet-class>com.worklog.InsertServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertServlet</servlet-name>
<url-pattern>/insert</url-pattern>
</servlet-mapping>
</web-app>
</element>
I was having the same issue. I was developing a mvc based REST API where there was no explicit html configuration or files. The API was using Swagger to generate a user interface. The problem started when I introduced Swagger version "3.0.0". I reverted back to Swagger "2.9.2" This solved my problem.
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
Please check context root cannot be empty.
If you're using eclipse:
right click, select properties, then web project settings. Check the context root cannot be empty

HTTP Status 404 - /SignInProject/LoginServlet [duplicate]

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
Or as below in Tomcat 10:
HTTP Status 404 — Not Found
Type: Status Report
Message: The requested resource (/servlet) is not available
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?
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
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:
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>
If you're using IntelliJ, this is what fixed it for me:
Go to the Tomcat configuration:
Configuration > Deployment Tab
Scroll down and add / to the Application Context dropdown
Solution for HTTP Status 404 in NetBeans IDE:
Right click on your project and go to your project properties, then click on run, then input your project relative URL like index.jsp.
Project->Properties
Click on Run
Relative URL:/index.jsp (Select your project root URL)
My issue was that my method was missing the #RequestBody annotation. After adding the annotation I no longer received the 404 exception.
Do the following two steps. I hope, it will solve the "404 not found" issue in tomcat server during the development of java servlet application.
Step 1: Right click on the server(in the server explorer tab)->Properties->Switch Location from workspace metadata to tomcat server
Step 2: Double Click on the server(in the server explorer tab)->Select Use tomcat installation option inside server location menu
I removed the old web library such that are spring framework libraries. And build a new path of the libraries. Then it works.
An old thread, but since I didn't find it elsewhere, here is one more possibility:
If you're using servlet-api 3.0+, then your web.xml must NOT include metadata-complete="true" attribute
This tells tomcat to map the servlets using data given in web.xml instead of using the #WebServlet annotation.
First of all, run your IDE as Admin. After that, right click the project folder -> Project Facets and make sure that the Java Version is set correct. On my PC. (For Example 1.8) Now it should work.
Don't just start your server, for example Wildfly, using the cmd. It has to be launched within the IDE and now visit your localhost URL. Example: http://localhost:8080/HelloWorldServlet/HelloWorld
The fix that worked for me is(if you are using Maven): Rightclick your project, Maven -> Update project. This might give you some other error with the JDK and other Libraries(in my case, MySQL connector), but once you fix them, your original problem should be fixed!
If you would like to open a servlet with javascript without using 'form' and 'submit' button, here is the following code:
var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});
Key:
1) button-id : The 'id' tag you give to your button in your html/jsp file.
2) full-servlet-path: The path that shows in the browser when you run the servlet alone
Mapping in web.xml is what i have done :-
If there's another package made for new program then we must mention :-
packagename.filename between opening and closing of servlet-class tag in xml file.
If you are mapping your files in xml and they are not working or showing errors , then comment on the annotation line of code in the respective files.
Both methods dont work with one another , so either i use annotation method of files mentioned when we create servlet or the way of mapping , then i delete or comment the annotation line. Eg:
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>performance.FirstServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/FirstServ</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>performance.SecondServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/SecondServ</url-pattern>
</servlet-mapping>
Commenting the annotation line of code in the respective file,if mapping in xml is done.
//#WebServlet("/FirstServ")
//#WebServlet("/SecondServ")
If someone is here who is using MySQL and felt that the code was working the previous day and now it doesn't, then I guess you must open MySQL CLI or MySQL Workbench and just make the connection to the database once. Once it gets connected, then the database also gets connected to the Java Application. I used to get the Hibernate Dialect error stating something wrong with com.mysql.jdbc.Driver. I think MySQL in some computers has a startup problem. This solved for me.
If you are a student and new to Java there might be some issue going on with your web.xml file.
Try removing the web.xml file.
Secondly check that your path variables are properly set or not.
Restart tomcat server Or your PC.
Your problem will be surely solved.
I was facing this issue too, I was receiving a 404 when accessing a URL pattern that I knew was linked to a Servlet. The reason is because I had 2 Servlets with their #WebServlet name parameter set as the same string.
#WebServlet(name = "ServletName", urlPatterns = {"/path"})
public class ServletName extends HttpServlet {}
#WebServlet(name = "ServletName", urlPatterns = {"/other-path"})
public class OtherServletName extends HttpServlet {}
Both of the name parameters are the same. If you're using the name parameter, make sure they are unique compared to all other Servlets on your application.
I had the same issue. Tried all of this but didn't help. I managed to solve this issue by adding element tags to beginning and end of the xml file. ill leave my xml file below for reference.
<?xml version="1.0" encoding="UTF-8"?>
<element>
<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">
<servlet>
<servlet-name>InsertServlet</servlet-name>
<servlet-class>com.worklog.InsertServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertServlet</servlet-name>
<url-pattern>/insert</url-pattern>
</servlet-mapping>
</web-app>
</element>
I was having the same issue. I was developing a mvc based REST API where there was no explicit html configuration or files. The API was using Swagger to generate a user interface. The problem started when I introduced Swagger version "3.0.0". I reverted back to Swagger "2.9.2" This solved my problem.
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
Please check context root cannot be empty.
If you're using eclipse:
right click, select properties, then web project settings. Check the context root cannot be empty

Spring Boot app deployed to Glassfish is giving strange results

As mentioned here, I am having a heck of a time getting my small Spring-Boot project to deploy "correctly" to Glassfish. It runs fine using the embedded Tomcat, but once I try and move it into my organization's environment (Glassfish 3.1.2) I get some strange behavior.
Thinking it was my code, I reverted to the time-tested "Hello World"-approach and built a super-basic app following this tutorial on Spring's blog.
I did make a few very minor deviations as I went along but nothing that should have affected the app like this at all.
The only major deviation I made was that I found I could not exclude "spring-boot-starter-tomcat" from "spring-boot-starter-web" -- when I tried to that, I got 2 errors in the STS "Markers"-tab:
The project was not built since its build path is incomplete. Cannot find the class file for javax.servlet.ServletContext. Fix the build path then try building this project
The type javax.servlet.ServletContext cannot be resolved. It is indirectly referenced from required .class files Application.java
If I cleaned the STS project, then ran Maven Clean, Update, Install the Install goal gave the following error:
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project test: Compilation failure [ERROR] /Users/brandon_utah/Utah Development/sts_workspaces/NidTools Rebooted/test/src/main/java/test/Application.java:[13,8] cannot access javax.servlet.ServletException [ERROR] class file for javax.servlet.ServletException not found
So what I did instead was include this dependency (which I found mentioned in several other SpringBoot resources):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
In this deployed fine to the embedded Tomcat and it did deploy to my Glassfish (local install) -- but with a whole bunch (about a half-dozen) errors similar to this one:
2014-04-03T16:23:48.156-0600|SEVERE: Class [ Lorg/springframework/jdbc/datasource/embedded/EmbeddedDatabase; ] not found. Error while loading [ class org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration ]
Most of them are SEVERE, but I am also getting a few with a WARNING:
2014-04-04T06:57:35.921-0600|WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: org/springframework/batch/core/configuration/annotation/BatchConfigurer
Except that I'm not referencing any of these missing classes anywhere in my project (other than what might be referenced by Spring Boot itself).
Also, the app doesn't quite work as expected. If I hit the RestController, I do get my page rendered as I expect -- but if I put any sort of System.out or Logger.log statement in the controller's method, that line of code seemingly never gets executed; by all appearances, it just gets skipped.
To demonstrate this problem, in my sample app's RestController I created a static counter. Then in the GET-/ method I increment that counter and System.out.println it's value. I also return the value as part of the Response.
And again, from a user's perspective, it seems to be working: the screen renders "Hello World" and in parentheses it shows the counter's value. I refresh the window, the counter increments. But nothing in the STS Console. And if I navigate to the Glassfish log for the app, nothing there either. Nothing. Nada. Zip. From what I can tell, something is mysteriously eating any attempt to log anything.
To add to the mystery, if I add a System.out to the SpringBootServletInitializer#configure(), that does make it to the Console. But if I declare a constructor in my RestController and include a System.out there, that one does not make it to the Console. For good measure, I even tried including a System.err in the constructor and a Logger.getAnonymousLogger.severe in the method; neither of those result in anything.
I should note that this also deploys and runs as expected using an external Tomcat.
I would very much appreciate any input, as it's not likely that I can convince my organization to deploy this to Tomcat nor use the embedded-Tomcat approach (due to politics and an overwhelming existing Glassfish environment).
My test project on Github is here.
This has been answered here: https://stackoverflow.com/a/29438821/508247
There is a bug in Glassfish 3.1.X. You need to include metadata-complete="true" in your web.xml root element.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
metadata-complete="true"
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">
</web-app>
I had this problem with Payara 5, I understand the problem became from Glassfish.
Versions:
Payara 5.192
Spring Boot 2.1.6
The solution worked for me:
I added this dependency in the pom.xml.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
My glassfish-web configuration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC ...>
<glassfish-web-app error-url="">
<class-loader delegate="true"/>
<jsp-config>
<property name="keepgenerated" value="true">
<description>Keep a copy of the generated servlet class' java code.</description>
</property>
</jsp-config>
<!-- set a friendly context root -->
<context-root>/micuenta-api</context-root>
<!-- Change the default character encoding from ISO-8859-1 to UTF-8 -->
<parameter-encoding default-charset="UTF-8"/>
</glassfish-web-app>

Resources