Assumes the following:
Java 17.
NetBeans 13.
Tomcat 10 added to NetBeans using Services > Servers > Add server…
In NetBeans: New project > Java with Maven > Web Application
Project Name: TomcatBasicDemo
Group Id: org.northcoder
Package: org.northcoder.tomcatbasicdemo
When presented with a choice of which Java EE version to use, just choose Java EE 7 Web. This is not what we will be using (it is very old) but it is (currently) the most current version available in the drop-down in NetBeans.
We will use the pom.xml
file to specify Jakarta EE 9…
(Just as a side note: After finishing creation of the new project, you can go to Project properties > run > JAVA EE Version - and there you will see a drop-down which has “Jakarta EE 9 Web” in its list - but that does not actually appear to change the application, as far as I can tell.)
The created project will contain a POM using the old Java EE 7 dependency. We will use the following cleaned-up POM for our needs, which replaces the old Java EE dependency:
|
|
Note the scope of the dependency, to support compilation, without conflicting with Tomcat-provided libs:
|
|
Note also the use of:
|
|
This means we do not need a web.xml
file - instead we will use annotations in the code (just for this demo).
We use this:
|
|
which causes the final WAR to be basic_demo.war
.
NetBeans creates a simple welcome page (index.html
):
|
|
We will test with this before adding a servlet.
NetBeans also creates a generated context.xml
file:
|
|
This appears to be needed for NetBeans to handle integration with Tomcat.
When you build and run the application, it creates a custom context in a file called TomcatBasicDemo.xml
in Tomcat’s /conf/Catalina/localhost/
. The contents are:
|
|
NetBeans uses a custom docbase
into which it deploys the webapp, and does not use the main /webapps
directory. That docbase
is in the NetBeans project’s target
directory.
When you run this webapp, you see the “Hello World!” message from the index.html
file at:
http://localhost:8080/TomcatBasicDemo/
Now we add a basic servlet - in this case using the @WebServlet
annotation:
|
|
With this new servlet, the original “Hello World!” message is still displayed at the previously shown URL - the context root of the web application.
But now the servlet’s message “Hello World Servlet” is displayed here:
http://localhost:8080/TomcatBasicDemo/hello
Additional Notes
Tomcat supported API versions.
There you see that Tomcat 10.0.x supports servlet spec 5.0 (Jakarta Servlet 5.0), which is supported by Jakarta EE 9.
The Jakarta servlet specification (v5.0) can be found here: https://jakarta.ee/specifications/servlet/5.0/jakarta-servlet-spec-5.0.html.
In the above specification document, the @WebServlet
annotation is described here.
You can also find useful notes (with examples) for the mapping rules between path patterns and servlets here.