Java Servlet Tutorial
This Java Servlet and JSP tutorial runs through the basic steps of setting up and running your first Java servlet. Follow the clear, simple instructions below to set up the Tomcat Server (needed to run Java servlets). Once your server is set up, move on to the tutorial’s second section to create, configure, compile, and deploy a basic “Hello World!” Java servlet.
Setting up an Environment (Tomcat)
Before we can start with our first Java servlet, we’ll need a stable environment in which to run it. That means installing the Apache Tomcat server. Follow the steps below.
1. Find the Latest Stable Release of Tomcat
Find out which version of Tomcat is the latest stable release. To do that, visit the Tomcat version page from Apache. The table at the top of the page shows the latest Tomcat version at the very top. Note that in the image below however, the top version is in the alpha testing phase. Therefore, at the time of this writing, the latest stable version was 8.5.15. The table also shows us which version of Java we’ll need.
2. Install the JRE or JDK
Now that we know which version of Tomcat we’ll be using, we also know which version of the Java Runtime Environment (JRE) we’ll need. If you’re still not sure, see the image above. For this JSP tutorial, we’ll use Tomcat 8.5.15, which means we’ll need JRE 8. (“7 andlater. “)
Note that JRE is part of JDK (Java Development Kit). To date there’s no way to simply update the JDK, so if you’re running an outdated version, the easiest course is to install the latest version of JDK.
You can install JRE here.
You can install JDK here.
3. Download Tomcat
To download Tomcat, visit the Tomcat download page. There are a lot of links on the page, but if this is your first time installing Tomcat, you’ll want the “zip” link under the “Core” heading for Windows, or “tar.gz” for Mac.
It’s not 100% crucial to choose zip over tar or vice versa, since the contents are the same, but Windows prefers zip.
4. Install Tomcat
Installing Tomcat is pretty simple.
For Windows: create a project directory. We’ll call it c:\projectOne. Unzip the Tomcat download file into that directory. It’ll show up in c:\projectOne\apache-tomcat-8.1.5 (or whatever version you’re installing). You can shorten this directory name to c:\projectOne\tomcat. From now on, we’ll just call it the Tomcat folder.
For Mac double click the downloaded file. Move the folder “apache-tomcat-8.1.5” (or similar) to your applications folder. You can shorten the folder name to “tomcat”. From now on, we’ll just call it the Tomcat folder.
5. (Windows Only) Create an Environment Variable
In Windows, we’ll need to make an environment variable named JAVA_HOME and point it to our JDK installed directory.
- Find the JDK install directory. Look in “c:\Program Files\Java\jdk1.8.0…”
- Set the environment variable by choosing Start > Control Panel > System and Security > System > Advanced System Settings > Switch to “Advanced” Tab > Environment Variables > System Variables > “New”.
- Under “Variable Name”, enter “JAVA_HOME”.
- For “Variable Value”, enter the name of your JDK install directory from step 1.
- Verify by restarting, then in a CMD shell issue “SET JAVA_HOME”. This should return the location of your new Java environment variable, which should be the install directory from step 1.
6. Configure the Tomcat Server
To configure Tomcat Server, first find the four configuration files. Look in the “conf” folder in the Tomcat install directory for the following files:
- web.xml
- server.xml
- tomcat-users.xml
- context.xml.
Backup all four files before you edit them.
Using a text editor like BBEdit, TextWrangler, or similar, open and edit the four files like so:
web.xml
Locate the code shown below in the web.xml file, then change “false” to “true” as shown in green. Note that you’re looking for the default servlet and the listings parameter. There’s a full copy of the file here. Use this configuration for learning only. Using it in production undermines proper security.
<!-- The default servlet for all web applications, that serves static -->
<!-- resources. It processes all requests that are not mapped to other -->
<!-- servlets with servlet mappings. -->
<servlet>
<servlet-name>
default
</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>
listings
</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
server.xml
In the server.xml file, find the code below. Change the default TCP port number from 8080 to any port number from 1024 to 65535. For this tutorial we’ll use 8888.
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="8888" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
tomcat-users.xml
We’ll alter the tomcat-users.xml file as shown below to enable Tomcat’s manager. (Pick your own username and password for the Tomcat manager. For more info about using the Manager app, see here.)
<tomcat-users>
<role rolename="manager-gui"/>
<user username="tomcatManager" password="XYZ" roles="manager-gui"/>
</tomcat-users>
context.xml
To the context.xml file, find the <Context> element and add the “reloadable=true” attribute. This will let us enable automatic reload after we make any changes to our code. Use this for testing only. In production, this would cause unnecessary overhead.
<Context reloadable="true">
......
......
</Context>
7. Start the Tomcat Server
Next we’ll need to start Tomcat Server.
In Windows: open a CMD shell and do the following to change to the right directory and start Tomcat:
c: // Assuming Tomcat is installed in the c: drive.
cd \projectOne\tomcat\bin // Assuming Tomcat is installed in \projectOne\tomcat.
startup // To start Tomcat
In Mac: open the Terminal, change to the right directory, and start Tomcat:
Cd /Applications/tomcat/bin // Change to the Tomcat install directory and bin
./catalina.sh run // Start tomcat server
8. Start a Tomcat Client
To access the Tomcat Server, we’ll need to start a client. In your browser, go to “http://localhost:8888” to reach the Tomcat Server welcome page. This works with a local machine. For remote access, substitute the actual IP address in place of “localhost”.
9. Test Your Tomcat Install
Test that Tomcat is working properly by browsing to http://localhost:8888/examples. Try running a few of the example servlets.
10. Shutdown Tomcat Server
Don’t simply close out of Tomcat by closing the active window. Instead, shutdown Tomcat properly.
In Windows: shutdown Tomcat Server by pressing Ctrl-C from the Tomcat console. Or from the CMD prompt, enter “shutdown” from the tomcat install directory and bin (c:\projectOne\tomcat\bin).
In Mac: press Ctrl-C from the Tomcat console. Or in the Terminal, enter “./shutdown.sh” from the tomcat install directory and bin (so, cd to /Applications/tomcat/bin).
Tomcat is Now Installed and Running
If you’ve followed the steps above, you should have a running Tomcat Server instance, complete with everything you need to run Java servlets. Let’s start with our first Java servlet (below).
Write Your First Java Servlet
A Java servlet is just a java program running in an HTTP server. Web users access it by browsing to the correct URL.
To write your first Java servlet, follow the steps below.
1. Create a WebApp and Directory Structure
The first thing we need to do is make a WebApp and directory structure for our Java servlet. We’ll call it helloWorld. In our tomcat folder (see step 4 above to locate this folder) find the webapps folder.
- In the webapps folder, make a new folder called helloWorld
- In the helloWord folder, make a new folder called WEB-INF .
- In the WEB-INF folder, make a new folder called classes .
Now we have tomcat folder > webapps > helloWorld > WEB-INF > classes. We’ll use them like this:
- helloWorld is our context root (also called the document base directory ) for our webapp. In it, we’ll put all HTML, CSS, scripts, images, and other files visble to web users.
- WEB-INF is for the application’s web.xml file.
- classes is for Java servlet class files.
After you’ve created the above folder structure, restart the server.
2. Create Your First Java Servlet
Once you’ve created the proper folder directory, create the servlet file. We’ll call it MyServlet.java, and we’ll save it in the “classes” directory. In the Tomcat folder, put the code below in \webapps\helloWorld\WEB-INF\classes\MyServlet.java.
Use the standard Hello World code from Tutorials Point to test your first servlet.
3. Compile Your Servlet
Compiling the first servlet isn’t easy. To compile it, we’ll need the Servlet API, located in our Tomcat folder, in /lib/servlet-api.jar.
In Windows: open a CMD shell and enter:
c:
cd \projectOne\tomcat\webapps/helloWorld\WEB-INF\classes
javac -cp .;C:\projectOne\tomcat\lib\servlet-api.jar MyServlet.java
// Where Tomcat is installed in c: \projectOne\tomcat
// Note: if any part of the path contains a blank space, put the entire path in quotes
// like this: "c:\folder one\tomcat\lib\servlet-api.jar"
In Mac: open Terminal and enter:
Cd /Applications/tomcat/webapps/helloWorld/WEB-INF/classes
Javac -cp .:/Applications/tomcat/lib/servlet-api.jar MyServlet.java
This will create a new class in the classes folder called MyServlet.class.
4. Configure the Servlet’s Request URL
To configure the URL for the MyServlet servlet, create a web.xml file for it and put it in webapps/helloWorld/WEB-INF. In the example below, we’re creating a new arbitrary servlet name “HiThere” and using it to map our recently created class file “MyServlet.class” to our new request URL “urlhello”.
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>HiThere</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<!-- Group all <servlet> elements together. Put them in front of all <servlet-mapping> elements -->
<servlet-mapping>
<servlet-name>HiThere</servlet-name>
<url-pattern>/urlhello</url-pattern>
</servlet-mapping>
</web-app>
The URL to access the above servlet is http://hostname:port/helloWorld/urlhello, where “helloWorld” is the name of our WebApp created in step 1 above.
Note that this configuration file applies only to our webapp “helloWorld.” To refresh the web.xml file, restart the Tomcat Server.
5. Invoke the Servlet
To invoke your new Java servlet, open a new browser window and browse to:
http://localhost:8888/helloWorld/urlhello
Conclusion
This Java tutorial for beginners gives you everything you need to set up a Tomcat environment and create your first Java servlet. You should be able to download and install the JRE/JDK and Tomcat Server, configure Tomcat, create, compile, and deploy your first Java servlet. If you notice problems or have suggestions, contact us and let us know.