Cannot run my servlet - Error 404

2019-09-16 09:06发布

问题:

This is my first attempt at making a Servlet Program which just displays text/html. I created the directories as is should be -

C:\Java_Advanced\DemoServlet

DemoServlet (folder) --WEB-INF ----classes (containing my .class file) ----lib ----web.xml --MyServlet.java (sitting in parallel with WEB-INF) I'm using tomcat apache 8.0.9 Here is my web.xml -

<web-app>
<servlet>
    <servlet-name>Hi</servlet-name>
    <servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Hi</servlet-name>
    <url-pattern>/run</url-pattern>
</servlet-mapping>
</web-app>

I made the war file (demo.war) of whatever was inside the DemoServlet. I started the Tomcat Apache service. I have given a port number other than the default 8080. I deployed my demo.war successfully (I am assuming because the message OK was printed above AND the application /demo's Running is coming to be true(I am told that a true state means there is no problem with the xml file)).

But still I open the new tab/window of the browser and type "localhost:myportnumber/demo/run" and all I get is HTTP Status Error 404 description: The requested resource is not available. I have tried refreshing with ctrl+F5, tried different browsers but still gives the same error.

What is wrong here? I searched over the internet and found something on this site: http://www.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html#TomcatDebug

(Scroll all the way to the bottom where it says for error 404) Everything is fine until 3.d point. The sub-directory mentioned as xxxx is "demo" in my case right? It does exist. And so does demo.war alongside it in parallel(is that how it should be?)

C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\demo

C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\demo.war

When I open the demo directory I DO NOT get a WEB-INF sub-directory. Instead there is a META-INF sub-directory and alongside it MyServlet.java file. Opening the META-INF folder there is a MANIFEST.MF file. Now what is that?? So, is this the reason for getting 404. Even if it is how do I fix it?

回答1:

It looks as if the structor of your war file is wrong.

The inside of the war file should at least look like:

WEB-INF/web.xml
WEB-INF/classes/MyServlet.class

Look in your war file. It is just a zip file.



回答2:

I'd strongly suggest using correct tool for building Java EE applications. You can use Eclipse with WTP. It will create correct project structure, allow you to more easily create and validate descriptors and you will be able to deploy your applications directly to server from the tool.

There must be a problem with current structure of your war file (its hard to tell from your description what is file/folder nesting) or building war itself.