Let's create a context step by step:
#1 create your context root directory
Let's suppose the name of your Tomcat install directory is catalina.
In C:\catalina\webapps create a new folder, say
myContext. Inside myContext, create a
WEB-INF folder (all caps). Inside WEB-INF, create a
classes and
lib folders.
Go to C:\catalina\conf and copy the web.xml file there to C:\catalina\webapps\myContext\WEB-INF. Edit this web.xml so that you will have
Go to C:\catalina\conf and edit the server.xml file. Look for this entry:
Under it, insert this:
Putting <!-- User Defined Contexts --> is strictly unnecessary, of course, but I find it helpful to find my contexts.
Now all we need to do is
test the setup. Create a simple
JSP called index.jsp:
and put it in C:\catalina\webapps\myContext.
Go to C:\catalina\bin and type startup to start Tomcat. A DOS window will appear with the following message:
indicating Tomcat started normally.
Open a browser and type in this URL:
http://localhost:8080/myContext If your index page shows up, you have defined your context successfully.
#2 Create a servlet and deploy it
Code a simple servlet for testing purposes:
Put TemplateServlet.java in C:\catalina\webapps\myContext\WEB-INF\classes.
Get your favorite
IDE, compile it, so that the resulting TemplateServlet.class is in the same folder.
(At this point some will argue that there is no need to put source code inside the classes folder, that you can use the javac -d option, etc. These are all valid points, but I'm trying to keep it simple now.)
Using the browser, type in this URL:
http://localhost:8080/myContext/servlet/TemplateServlet and
you should get Test.
Note that we have NOT edited the web.xml file.
#3 registering the servlet in the web.xml file
Go to C:\catalina\webapps\myContext\WEB-INF and edit the web.xml so that we have:
Use only Notepad or DOS edit. Do NOT use WordPad or other editors as it will change the formatting.
We have now "registered" the TemplateServlet with Tomcat with the alias
template and it has the servlet path
/test.
Please note that if you edit any Tomcat config file like web.xml or server.xml you have to restart Tomcat. After shutting Tomcat down, do not start up again immediately, since it is still releasing resources. The most common error of this type is a bind exception on the 8080 HTTP port that Tomcat uses.
After restarting Tomcat, type in this URL now:
http://localhost:8080/myContext/test and you should get the same servlet. Alternatively, you could use its alias, e.g
http://localhost:8080/myContext/servlet/template