Java Servlet Tutorial - How To Install Tomcat 8
Java Servlet Tutorial - How To Install Tomcat 8
and Get Started with Java Servlet 2.2 STEP 1: Download and Install T
2.3 STEP 2: Create an Environmen
This practical can be completed in a 3-hour session. 4. (Skip Unless...) How to Debug?
1. Introduction
A webapp is typically a 3-tier (or multi-tier) client-server database application run over the Internet as illustrated in the diagram below. It comprises five
components:
1. HTTP Ser ver : E.g., Apache HTTP Server, Apache Tomcat Server, Microsoft Internet Information Server (IIS), nginx, Google Web Server (GWS), and
others.
2. HTTP Client (or Web Browser) : E.g., Internet Explorer (MSIE), FireFox, Chrome, Safari, and others.
3. Database : E.g., Open-source MySQL, PostgreSQL, Apache Derby, mSQL, SQLite, OpenOffice's Base; Commercial Oracle, IBM DB2, SAP SyBase,
Microsoft SQL Server, Microsoft Access; and others.
4. Client-Side Programs : Could be written in HTML Form, JavaScript, and others.
5. Ser ver-Side Programs : Could be written in Java Servlet/JSP, ASP, PHP, Perl, Python, JavaScript, and others.
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 1/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 2/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
Tomcat was originally written by James Duncan Davison (then working in Sun Microsystem) in 1998, based on an earlier Sun's server called Java Web
Server (JWS). It began at version 3.0 after JWS 2.1 it replaced. Sun subsequently made Tomcat open-source and gave it to Apache.
2. How to Install Tomcat and Get Started with Java Servlet Programming
For Windows
1. Goto http://tomcat.apache.org ⇒ Under "Tomcat 9.0.{xx} Released", where {xx} is the latest update number ⇒ Click "Download" ⇒ Under
"9.0.{xx}" ⇒ Binary Distributions ⇒ Core ⇒ "zip" (e.g., "apache-tomcat-9.0.{xx}.zip", about 11 MB).
2. UNZIP (right-click ⇒ Extract All) the downloaded file into your project directory "c:\myWebProject". Tomcat shall be unzipped into
directory "c:\myWebProject\apache-tomcat-9.0.{xx}".
3. For EASE OF USE, we shall shorten and rename this directory to "c:\myWebProject\tomcat".
Take note of Your Tomcat Installed Directory. Hereafter, I shall refer to the Tomcat installed directory as <TOMCAT_HOME>.
For macOS
1. Goto http://tomcat.apache.org ⇒ Under "Tomcat 9.0.{xx} Released", where {xx} is the latest update number ⇒ Click "Download" ⇒ Under
"9.0.{xx}"⇒ Binary distribution ⇒ Core ⇒ "tar.gz" (e.g., "apache-tomcat-9.0.{xx}.tar.gz", about 10.5 MB).
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 3/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
2. To install Tomcat:
a. Double-click the downloaded tarball (e.g., "apache-tomcat-9.0.{xx}.tar.gz") to expand it into a folder (e.g., "apache-tomcat-
9.0.{xx}").
b. Move the extracted folder (e.g., "apache-tomcat-9.0.{xx}") to your project directory "~/myWebProject".
c. For EASE OF USE, we shall shorten and rename this folder to "tomcat", i.e., "~/myWebProject/tomcat".
Take note of Your Tomcat Installed Directory. Hereafter, I shall refer to the Tomcat installed directory as <TOMCAT_HOME>.
For Ubuntu
Read "How to Install Tomcat on Ubuntu". You need to switch between these two articles.
For academic learning, I recommend "zip" (or "tar.gz") package, as you could simply delete the entire directory when Tomcat is no longer needed
(without running any un-installer). You are free to move or rename the Tomcat's installed directory. You can install (unzip) multiple copies of Tomcat in the
same machine.
Tomcat's Sub-Directories
Take a quick look at the Tomcat installed directory. It contains the these sub-directories:
bin : contains the binaries and scripts (e.g., startup.bat and shutdown.bat for Windows; startup.sh and shutdown.sh for Unixes and macOS).
conf : contains the system-wide configuration files, such as server.xml, web.xml, and context.xml.
webapps : contains the webapps to be deployed. You can also place the WAR (Webapp Archive) file for deployment here.
lib : contains the Tomcat's system-wide library JAR files, accessible by all webapps. You could also place external JAR file (such as MySQL JDBC Driver)
here.
logs : contains Tomcat's log files. You may need to check for error messages here.
work : Tomcat's working directory used by JSP, for JSP-to-Servlet conversion.
(For Windows)
You need to create an environment variable (system variable available to all applications) called "JAVA_HOME", and set it to your JDK installed
directory.
(For macOS)
Skip this step. No need to do anything.
1. server.xml
2. web.xml
3. context.xml
The default TCP port number configured in Tomcat is 8080, you may choose any number between 1024 and 65535, which is not used by existing
applications. We shall choose 9999 in this article. (For production server, you should use port 80, which is pre-assigned to HTTP server as the default port
number.)
Locate the following lines (around Line 69) that define the HTTP connector, and change port="8080" to port="9999".
-->
connectionTimeout="20000"
redirectPort="8443" />
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 4/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
We shall enable directory listing by changing "listings" from "false" to "true" for the "default" servlet. This is handy for test system, but not for
production system for security.
Locate the following lines (around Line 122) that define the "default" servlet; and change the "listings" from "false" to "true".
<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>
Locate the <Context> start element (around Line 19), and change it to:
......
......
</Context>
For Windows
I shall assume that Tomcat is installed in "c:\myWebProject\tomcat". Launch a CMD shell and issue:
c: // Change drive
For macOS
I assume that Tomcat is installed in "~/myWebProject/tomcat". To start the Tomcat server, open a new "Terminal" and issue:
A new Tomcat console window appears (with Java's coffee-cup logo as icon). Study the messages on the console. Look out for the Tomcat's port number.
Double check that Tomcat is running on port 9999 as configured.
Error messages will be sent to this console. System.out.println() issued by your Java servlets will also be sent to this console.
............
............
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 5/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
(Optional) Try issuing URL http://localhost:9999/examples to view the servlet and JSP examples. Try running some of the servlet examples.
For Windows
For macOS
WARNING : You MUST properly shutdown the Tomcat. DO NOT kill the CAT by pushing the window's "CLOSE" button.
2. Under "hello", create a sub-directory "WEB-INF" (case sensitive, a "dash" not an underscore) (i.e., "
<TOMCAT_HOME>\webapps\hello\WEB-INF").
3. Under "WEB-INF", create a sub-sub-directory "classes" (case sensitive, plural) (i.e., "
<TOMCAT_HOME>\webapps\hello\WEB-INF\classes").
You need to keep your web resources (e.g., HTMLs, CSSs, images, scripts, servlets, JSPs) in the proper directories:
"hello": The is called the context root (or document base directory) of your webapp. You should keep all your HTML files
and resources visible to the web users (e.g., HTMLs, CSSs, images, scripts, JSPs) under this context root.
"hello/WEB-INF": This directory, although under the context root, is not visible to the web users. This is where you keep your application's web
descriptor file "web.xml".
"hello/WEB-INF/classes": This is where you keep all the Java classes such as servlet class-files.
You need to RE-START your Tomcat server to pick up the hello webapp. Check the Tomcat's console to confirm that "hello" application has been
properly deployed:
......
......
You can issue the following URL to access the web application "hello":
http://localhost:9999/hello
You should see the directory listing of the directory "<TOMCAT_HOME>\webapps\hello", which shall be empty at this point of time. Take note that we have
earlier enabled directory listing in "web.xml". Otherwise, you will get an error "404 Not Found".
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 6/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
Create the following HTML page and save as "HelloHome.html"
in your webapp's root directory "hello".
1 <!DOCTYPE html>
2 <html>
4 <body>
5 <h1>Hello, world!</h1>
7 </body>
8 </html>
http://localhost:9999/hello/HelloHome.html
http://localhost:9999/hello
The server will return the directory listing of your base directory. You can then click on "HelloHome.html".
http://localhost:9999/hello
Now, the server will redirect the directory request to "index.html", if the root directory contains an "index.html", instead of serving the directory listing.
Rename "index.html" back to "HelloHome.html", so that you could see get directory listing for convenience.
You can check out the home page of your peers by issuing:
http://YourPeerHostnameOrIPAddr:9999/hello
http://YourPeerHostnameOrIPAddr:9999/hello/HelloHome.html
with a valid "YourPeerHostnameOrIPAddr", provided that your peer has started his tomcat server and his firewall (and the network) does not block your
access. You can use command such as "ipconfig" (Windows), "ifconfig" (macOS and Unix) to find your IP address.
(Skip Unless...) The likely errors are "Unable to Connect", "Internet Explorer cannot display the web page", and "404 File Not Found". Read "How to
Debug" section.
Before you proceed, I shall assume that you are familiar with Java Programming and have installed the followings:
1. JDK (Read "How to install JDK and Get Started").
2. A programming text editor, such as Sublime Text or Atom.
In this example, we are going to write a Java servlet called HelloServlet, which says "Hello, world!". We will configure such that web users can invoke this
servlet by issuing URL http://ip_addr:port/hello/sayhello from their browser, as illustrated:
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 7/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
Write the following source codes called "HelloServlet.java" and save it under your application "classes" directory (i.e., "
<TOMCAT_HOME>\webapps\hello\WEB-INF\classes\HelloServlet.java"). This servlet says "Hello", echoes some request information, and prints a
random number upon each request.
1 // To save as "<TOMCAT_HOME>\webapps\hello\WEB-INF\classes\HelloServlet.java"
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import javax.servlet.annotation.*;
7 @WebServlet("/sayhello") // Configure the request URL for this servlet (Tomcat 7/Servlet 3.0 upwards)
9
10 // The doGet() runs once per HTTP GET request to this servlet.
11 @Override
14
16 response.setContentType("text/html");
17 // Allocate a output writer to write the response message into the network socket
19
21 out.println("<!DOCTYPE html>");
22 out.println("<html>");
23 out.println("<head><title>Hello, World</title></head>");
24 out.println("<body>");
33 out.println("</body></html>");
35 }
36 }
Take note that in Line 7, we configure this HelloServlet to URL "/sayhello" via annotation @WebServlet("/sayhello"), which is applicable to Tomcat
7 onwards. In other words, the full URL shall be http://ip_addr:port/hello/sayhello to trigger this HelloServlet.
(For Windows)
c:
cd \myWebProject\tomcat\webapps\hello\WEB-INF\classes
(For macOS)
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 8/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
cd ~/myWebProject/tomcat/webapps/hello/WEB-INF/classes
// Compile with Servlet API - Need to use $HOME instead of ~ in the "javac" command
Use your "File Explorer" to check the "webapps/hello/WEB-INF/classes" folder to make sure that "HelloServlet.class" has been created in
the right place.
To invoke this servlet, start a browser, and issue the request URL configured as follows:
http://localhost:9999/hello/sayhello
You shall see the output of the servlet displayed in your web browser.
Refresh the browser, you shall see a new random number upon each refresh. In other word, the doGet() method of the servlet runs once per request.
(For macOS's Safari browser) You need to enable "Developer Menu" under the "Preferences" to enable the "View Source" menu.
<!DOCTYPE html>
<html>
<head><title>Hello, World</title></head>
<body>
<h1>Hello, world!</h1>
<p>Protocol: HTTP/1.1</p>
<p>PathInfo: null</p>
</body>
</html>
(Skip Unless...) The likely errors are "404 File Not Found" and "500 Internal Server Error". Read "How to debug" Section.
For Firefox/Chrome, press F12 (called F12 debugger) to enable "Web Console" or "Developer Tool". Choose "Console" or "Network" pane. Enter URL
http://localhost:9999/hello/sayhello (or refresh). Under "Net" or "Network". Expand the link http://localhost:9999/hello/sayhello. A HTTP
message consists of a header and a body. Inspect the request header and body; as well as the response header and body.
Host: localhost:9999
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Cache-Control:max-age=0
Connection: keep-alive
Upgrade-Insecure-Requests: 1
HTTP/1.1 200 OK
Content-Length: 286
Content-Type: text/html;charset=ISO-8859-1
<!DOCTYPE html>
<html>
<head><title>Hello, World</title></head>
<body>
<h1>Hello, world!</h1>
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 9/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
<p>Request URI: /hello/sayhello</p>
<p>Protocol: HTTP/1.1</p>
<p>PathInfo: null</p>
</body></html>
Step 7(a) Setup a Database on MySQL (Already done in the MySQL exercises)
Start your MySQL server. Take note of the server's port number. I shall assume that the MySQL server is running on port 3306, whereas the Tomcat is
running on port 9999.
c:
cd \myWebProject\mysql\bin
mysqld --console
// For macOS
Start a MySQL client. I shall assume that there is a user called "myuser" with password "xxxx".
c:
cd \myWebProject\mysql\bin
mysql -u myuser -p
cd /usr/local/mysql/bin
./mysql -u myuser -p
Run the following SQL statements to create a database called "ebookshop", with a table called "books" with 5 columns: id, title, author, price, qty.
use ebookshop;
id int,
title varchar(50),
author varchar(50),
price float,
qty int,
insert into books values (1001, 'Java for dummies', 'Tan Ah Teck', 11.11, 11);
insert into books values (1002, 'More Java for dummies', 'Tan Ah Teck', 22.22, 22);
insert into books values (1003, 'More Java for more dummies', 'Mohammad Ali', 33.33, 33);
insert into books values (1004, 'A Cup of Java', 'Kumar', 55.55, 55);
insert into books values (1005, 'A Teaspoon of Java', 'Kevin Jones', 66.66, 66);
Step 7(b) Install MySQL JDBC Driver (Already done in the previous JDBC exercises)
You need to download MySQL JDBC driver if you have not done so. Read "Installing the MySQL JDBC Driver".
Step 7(c) Copy the MySQL JDBC Driver to Tomcat's "lib" (IMPORTANT!!! DON'T MISS THIS STEP!!!)
Copy the MySQL JDBC Driver JAR file "mysql-connector-java-8.0.{xx}.jar" into Tomcat's lib directory, i.e., "c:\myWebProject\tomcat\lib" (for
Windows) or "~\myWebProject\tomcat\lib" (macOS).
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 10/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
1 <!DOCTYPE html>
2 <html>
3 <head>
5 </head>
6 <body>
9 <b>Choose an author:</b>
14 </form>
15 </body>
16 </html>
You can browse the HTML page by issuing the following URL:
http://localhost:9999/hello/querybook.html
Check a box (e.g., "Tan Ah Teck") and click the "Search" button. You are expected to get an error "404 File Not Found", as you have yet to write the server-
side program.
But observe the URL in the browser's navigation bar, reproduced as follows:
http://localhost:9999/hello/query?author=Tan+Ah+Teck
2. a so-called query string begins with a '?', followed by "name=value" pair extracted from the selected <input> tag (i.e., author=Tan+Ah+Teck). Take
note that blanks are replaced by '+' (or %20 - a '%' followed by ASCII code of blank in hex), because blanks are not allowed in the URL.
If you check two boxes (e.g., "Tan Ah Teck" and "Mohammad Ali"), you will trigger a query string with two "name=value" pairs separated by an '&'.
http://localhost:9999/hello/query?author=Tan+Ah+Teck&author=Mohammad+Ali
Step 7(e) Write the Ser ver-side Database Quer y Ser vlet
The next step is to write a Java servlet, which responses to the client’s request by querying the database and returns the query results.
1 // To save as "<TOMCAT_HOME>\webapps\hello\WEB-INF\classes\QueryServlet.java".
2 import java.io.*;
3 import java.sql.*;
4 import javax.servlet.*;
5 import javax.servlet.http.*;
6 import javax.servlet.annotation.*;
7
8 @WebServlet("/query") // Configure the request URL for this servlet (Tomcat 7/Servlet 3.0 upwards)
10
11 // The doGet() runs once per HTTP GET request to this servlet.
12 @Override
16 response.setContentType("text/html");
17 // Get a output writer to write the response message into the network socket
19
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 11/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
20 // Print an HTML page as the output of the query
21 out.println("<!DOCTYPE html>");
22 out.println("<html>");
23 out.println("<head><title>Query Response</title></head>");
24 out.println("<body>");
25
26 try (
29 "jdbc:mysql://localhost:3306/ebookshop?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC",
32
33 // Step 2: Allocate a 'Statement' object in the Connection
35 ) {
40
41 out.println("<h3>Thank you for your query.</h3>");
42 out.println("<p>Your SQL statement is: " + sqlStr + "</p>"); // Echo for debugging
44
45 // Step 4: Process the query result set
46 int count = 0;
47 while(rset.next()) {
49 out.println("<p>" + rset.getString("author")
52 count++;
53 }
55 } catch(Exception ex) {
58 ex.printStackTrace();
60
61 out.println("</body></html>");
62 out.close();
63 }
64 }
Take note that in Line 8, we configure this QueryServlet to URL "/query" via annotation @WebServlet("/query"). In other words, the full URL to
trigger this QueryServlet is http://ip_addr:port/hello/query, which corresponds to the "action" attribute of the <form> tag of the
"querybook.html" written earlier.
// Windows
c:
cd \myWebProject\tomcat\webapps\hello\WEB-INF\classes
// macOS
cd ~/myWebProject/tomcat/webapps/hello/WEB-INF/classes
Use a "File Explorer", verify that "QueryServlet.class" was generated in the "classes" directory.
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 12/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
Step 7(f ) Invoke the Ser vlet from the Client-Side Form with Quer y String
Issue the following URL to browse the HMTL form "querybook.html" that you have created earlier:
http://localhost:9999/hello/querybook.html
Select an author (e.g., "Tan Ah Teck") and click the submit button, which activates the following URL coded in the <form>'s "action" attribute, together
with a query string of NAME=VALUE pair:
http://localhost:9999/hello/query?author=Tan+Ah+Teck
The above query string has a NAME=VALUE pair of author=Tan+Ah+Teck. In Line 38, the method request.getParameter("author") returns a string
"Tan Ah Teck", which is inserted into the SQL SELECT command:
select * from books where author = 'Tan Ah Teck' and qty > 0 order by price desc
In this way, the SQL SELECT command is formed based on the user's selection in the form.
(Skip Unless...) If you see a blank screen or incorrect output, look for error messages from the Tomcat console!!! Check "How to debug"
Database Servlet Errors.
The annotation @WebServlet("url") for deploying servlet is supported from Tomcat 7/Servlet 3.0. Prior to Tomcat 7, you need to deploy servlets via
deployment descriptors in the web.xml configuration file.
Create the following configuration file called "web.xml", and save it under "webapps\hello\WEB-INF" (i.e., "<TOMCAT_HOME>\webapps\hello\WEB-
INF\web.xml").
2 <web-app version="3.0"
3 xmlns="http://java.sun.com/xml/ns/javaee"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
9 <servlet>
10 <servlet-name>HelloWorld</servlet-name>
11 <servlet-class>HelloServlet</servlet-class>
12 </servlet>
13
16
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 13/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
17 <servlet-mapping>
18 <servlet-name>HelloWorld</servlet-name>
19 <url-pattern>/sayhello</url-pattern>
20 </servlet-mapping>
21 </web-app>
In the above configuration, a servlet having a class file "HelloServlet.class" is mapped to request URL "/sayhello" (via an arbitrary servlet-name
"HelloWorld"), under this web application "hello". In other words, the complete request URL for this servlet is
"http://hostname:port/hello/sayhello".
This configuration file, saved under your webapp "hello", is applicable only to this particular webapp "hello".
Note: For EACH servlet, you need to write a pair of <servlet> and <servlet-mapping> elements with a common but arbitrary <servlet-name>. Take
note that all the <servlet> elements MUST be grouped together and placed IN FRONT of the <servlet-mapping> elements.
Always...
1. Re-start Tomcat (and Check the Tomcat's console for Error Messages)!!!
2. Re-start your browser!!!
3. Refresh your browser using Cntl-F5 (instead of refresh button or simply F5) to get a fresh copy, instead of from the cache.
4. Check your spelling! Always assume that all programs are case-sensitive. Don't type, copy and paste if possible!
5. and MOST IMPORTANTLY - Find the ERROR MESSAGE!!!
a. Check the Error Messages on Tomcat's Console. Most of the error messages have a few screens of lines. You need to scroll up slowly from the
last line to look for the FIRST LINE of the error messages.
The last packet sent successfully to the server was 0 milliseconds ago.
The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 14/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
......
......
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
b. Check the Tomcat's log files, located at "<TOMCAT_HOME>\logs". The "catalina.yyyy-mm-dd.log" shows the Tomcat's startup messages. Also
check the "localhost.yyyy-mm-dd.log".
6. If things were running fine until the lightning strikes, ask yourself "What have I changed?"
POSSIBLE SOLUTIONS:
1. Run the script "configtest.bat" (for Windows) or "./configtest.sh" (for macOS/Linux) to check
3. Start the tomcat in the debugging mode by running "catalina debug" (or ./catalina.sh debug) and
type "run" in the "jdb" prompt. Look for the error messages.
(java.net.BindException: Address already in use: JVM_Bind), kill the Tomcat process (See below).
5. If the error messages indicate that another application is running on the Tomcat's port numbers,
You can issue command "netstat -an" to check the status of all the ports.
ERROR MESSAGE:
POSSIBLE SOLUTIONS:
You can issue command "netstat -an" to check the status of all the ports.
ERROR MESSAGE:
POSSIBLE SOLUTIONS:
1. Check if JAVA_HOME is properly defined, via command "set JAVA_HOME" (for Windows)
2. Define environment variable JAVA_HOME according to "Step 2: Create an Environment Variable JAVA_HOME".
ERROR MESSAGE:
POSSIBLE SOLUTIONS:
In Linux/macOS, you may issue "ps aux | grep tomcat" to locate the Tomcat process. Note down the process ID (pid). You can kill the Tomcat
process via "kill -9 pid".
POSSIBLE SOLUTION:
But Tomcat server cannot find the HTML file or Servlet that your requested.
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 15/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
POSSIBLE SOLUTION:
b. Check the Tomcat console to make sure that your application "xxxx" has been deployed.
d. Open the "xxxx" directory, check if sub-directory "WEB-INF" (uppercase with a dash) exists.
g. Check if you have compiled the servlet. That is, the .class exisits (NOT .java).
POSSIBLE SOLUTION:
Error 500 should have triggered many error message in the Tomcat's console.
ERROR MESSAGE: Error 505: GET (or POST) method not supported
POSSIBLE SOLUTION:
Check you servlet to make sure that you have defined a doGet() (or doPost()) method.
ERROR MESSAGE: class xxxx is public, should be declared in a file named xxxx.java
CAUSES/SOLUTION:
In Java, the filename must be the same as the classname with extension of ".java".
CAUSES/SOLUTION:
The Java Servlet library is missing. Read "Step 6(b) Compiling the Servlet"
ERROR MESSAGE:
The servlets named [xxx] and [yyy] are both mapped to the url-pattern [zzz] which is not permitted
CAUSES/SOLUTION:
Check to ensure that no two servlets are mapping to the SAME URL in @WebServlet("url")
POSSIBLE SOLUTION:
Check if you have done Step 7(c) Copy the MySQL JDBC Drive to Tomcat's "lib".
POSSIBLE SOLUTION:
ERROR MESSAGE: Access denied for user 'myuser'@'localhost' (using password: YES)
POSSIBLE SOLUTION:
POSSIBLE SOLUTION:
ERROR MESSAGE: The server time zone value '...' is unrecognized or represents more than one time zone
POSSIBLE SOLUTION:
POSSIBLE SOLUTION:
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 16/17
3/2/22 18:36 Java Servlet Tutorial - How to Install Tomcat 8 (on Windows, Mac OS and Ubuntu) and Get Started with Java Servlet Programming
4. "Introduction to Java Database (JDBC) Programming".
5. Jason Brittain, Ian F. Darwin, "Tomcat The Definitive Guide", 2nd eds, OReilly, 2007.
Latest version tested: Tomcat 9.0.41, MySQL 8.0.23, JDK 15.0.2, Windows 10, macOS 10.15, Ubuntu 18.04LTS
Last modified: March, 2021
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan ([email protected]) | HOME
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html 17/17