views:

476

answers:

2

I am trying to make servlet.

I have installed tomcat6 on ubuntu with admin examples and docs. I am able to run the examples provided. But when i try to make my own servlet it doesnt work.

I did following steps

Under the ROOT i create folder with

-ROOT
----myapp
------WEB-INF
---------classes

I made two files one is index.html which have a button and action on form to call the servlet. Second is .java file. I compiled the .java file and .class is done. So now tree look like

-ROOT
----myapp
------index.html
------WEB-INF
---------classes
-----------TestServ.java
-----------TestServ.class

Now i open this in browser using http://localhost:8080/myapp

It shows up with index.html page with button. But when i click on the button it says

Error 404: http://localhost:8080/myapp/TestServ not found !!

I dont know where m going wrong. I have set the CATALINA_HOME too. But still this problem continue.

+5  A: 

You need to create a web.xml in the WEB-INF directory, and define the servlet mapping in web.xml, so that the myapp/TestServ URL is forwarded to the TestServ servlet class.

Here is a page describing web.xml, and has the example and elements you need to set up. For your class, these elements will probably look something like this:

<servlet>
    <servlet-name>testServ</servlet-name>
    <servlet-class>TestServ</servlet-class>
</servlet>

<servlet-mapping>
     <!-- For any URL starting with /content/, the rewriter servlet will be called -->
     <servlet-name>testServ</servlet-name>
     <url-pattern>/TestServ</url-pattern>
</servlet-mapping>
Kaleb Brasee
thnks its working now .. sorry for a bit late reply
asb
+1  A: 

You shouldn't be deploying any of your code under ROOT.

You shouldn't have any Java class in the default package. Try putting your TestServ.java in a package.

Your deployment should NOT include any .java files.

You've got to register your servlet properly in web.xml. Include a mapping to a particular URL.

Your best best is to create a WAR file named myapp.war, which includes WEB-INF/classes and WEB-INF/lib and a web.xml for your situation. Put that in the Tomcat /webapps and start the container. If you've registered your servlet properly you should be able to access it via http://localhost:8080/myapp/TestServ.

I'd read the deployment docs carefully.

duffymo
+1 for mentioning that packageless servlets are failure. It should however be mentioned that they might work in certain environments, but that you should never rely on that. Always put classes in packages, simply because you can't access packageless classes from other classes on the usual Java way
BalusC
What's wrong with deploying an app as ROOT.war?
Kaleb Brasee
Ys but it works without package too. Thanks any way
asb
Your app isn't ROOT - should have its own context. It's easy enough to do, so why not?
duffymo