1 介绍
A typical use case is:
1.2 Hypertext Transfer Protocol (HTTP)
1.3 Apache Tomcat HTTP Server
Apache Tomcat is a Java-capable HTTP server, which could execute special Java programs known as "Java Servlet" and "Java Server Pages (JSP)". Tomcat is an open-source project, under the "Apache Software Foundation" (which also provides the most use, open-source, industrial-strength Apache HTTP Server). The mother site for Tomcat is http://tomcat.apache.org. Alternatively, you can find tomcat via the Apache mother site @ http://www.apache.org.
Tomcat was originally written by James Duncan Davison (then working in Sun) 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.
The various Tomcat releases are:
2.1 STEP 0: Create a Directory to Keep all your Works
I shall assume that you have created a directory called "c:\myWebProject
" (for Windows) or "~\myWebProject
" (for Mac OS X) in your earlier exercises. Do it otherwise. This step is important; otherwise, you will be out-of-sync with this article and will not be able to find your files later.
2.2 STEP 1: Download and Install Tomcat
For Windows
zip
" (e.g., "apache-tomcat-9.0.{xx}.zip
", about 11 MB).c:\myWebProject
". Tomcat shall be unzipped into directory "c:\myWebProject\apache-tomcat-9.0.{xx}
".c:\myWebProject\tomcat
".Take note of Your Tomcat Installed Directory. Hereafter, I shall refer to the Tomcat installed directory as
.
For Mac OS X
tar.gz
" (e.g., "apache-tomcat-9.0.{xx}.tar.gz
", about 10.5 MB).apache-tomcat-9.0.{xx}.tar.gz
") to expand it into a folder (e.g., "apache-tomcat-9.0.{xx}
").apache-tomcat-9.0.{xx}
") to your project directory "~/myWebProject
".~/myWebProject/tomcat
".Take note of Your Tomcat Installed Directory. Hereafter, I shall refer to the Tomcat installed directory as
.
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:
startup.bat
and shutdown.bat
for Windows; startup.sh
and shutdown.sh
for Unixes and Mac OS X).server.xml
, web.xml
, and context.xml
.2.3 STEP 2: Create an Environment Variable JAVA_HOME
(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.
Follow the steps HERE!
(For Mac OS)
Skip this step. No need to do anything.
2.4 STEP 3: Configure the Tomcat Server
The Tomcat configuration files, in XML format, are located in the "conf
" sub-directory of your Tomcat installed directory, e.g. "c:\myWebProject\tomcat\conf
" (for Windows) or "~/myWebProject/tomcat/conf
" (for Mac OS X). The important configuration files are:
server.xml
web.xml
context.xml
Make a BACKUP of the configuration files before you proceed!!!
Step 3(a) "conf\server.xml" - Set the TCP Port Number
Use a programming text editor (e.g., Sublime Text, Atom) to open the configuration file "server.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"
.
Step 3(b) "conf\web.xml" - Enable Directory Listing
Again, use a programming text editor to open the configuration file "web.xml
".
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 108) that define the "default
" servlet; and change the "listings
" from "false
" to "true
".
default org.apache.catalina.servlets.DefaultServlet debug 0 listings true 1
Step 3(c) "conf\context.xml" - Enabling Automatic Reload
We shall add the attribute reloadable="true"
to the
element to enable automatic reload after code changes. Again, this is handy for test system but not recommended for production, due to the overhead of detecting changes.
Locate the
start element (around Line 19), and change it to
.
reloadable="true"> ...... ......
2.5 STEP 4: Start Tomcat Server
The Tomcat's executable programs and scripts are kept in the "bin
" sub-directory of the Tomcat installed directory.
Step 4(a) Start Server
For Windows
I shall assume that Tomcat is installed in "c:\myWebProject\tomcat
". Launch a CMD shell and issue:
c: // Change drive cd \myWebProject\tomcat\bin // Change directory to your Tomcat's binary directory startup // Run startup.bat to start tomcat server
For Mac OS
I assume that Tomcat is installed in "~/myWebProject/tomcat
". To start the Tomcat server, open a new "Terminal" and issue:
cd ~/myWebProject/tomcat/bin // Change directory to your Tomcat's binary directory ./catalina.sh run // Run catalina.sh to start tomcat server
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.
............ ............ xxxxx INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-9999"] xxxxx INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"] xxxxx INFO [main] org.apache.catalina.startup.Catalina.start Server startup in [1325] ms
(Skip Unless ...) Cannot Start Tomcat: Read "How to Debug".
Step 4(b) Start a Client to Access the Server
Start a browser (Firefox, Chrome) as an HTTP client. Issue URL "http://localhost:9999
" to access the Tomcat server's welcome page. The hostname "localhost
" (with IP address of 127.0.0.1
) is meant for local loop-back testing within the same machine. For users on the other machines over the net, they have to use the server's IP address or DNS domain name in the form of "http://serverHostnameOrIPAddress:9999
".
(Optional) Try issuing URL http://localhost:9999/examples
to view the servlet and JSP examples. Try running some of the servlet examples.
Step 4(c) Shutdown Server
For Windows
You can shutdown the tomcat server by either:
\bin\shutdown.bat
" script. Open a new "cmd" and issue: c: // Change the current drive cd \myWebProject\tomcat\bin // Change directory to your Tomcat's binary directory shutdown // Run shutdown.bat to shutdown the server
For Mac OS
To shutdown the Tomcat server:
/bin/shutdown.sh
" script. Open a new "Terminal" and issue: cd ~/myWebProject/tomcat/bin // Change current directory to Tomcat's bin directory ./shutdown.sh // Run shutdown.sh to shutdown the server
WARNING: You MUST properly shutdown the Tomcat. DO NOT kill the CAT by pushing the window's "CLOSE" button.
2.6 STEP 5: Develop and Deploy a WebApp
Step 5(a) Create the Directory Structure for your WebApp
Let's call our first webapp "hello
". Goto Tomcat's "webapps
" sub-directory and create the following directory structure for your webapp "hello
" (as illustrated):
webapps
", create your webapp's root directory "hello
" (i.e., "\webapps\hello
").hello
", create a sub-directory "WEB-INF
" (case sensitive, a "dash" not an underscore) (i.e., "\webapps\hello\WEB-INF
").WEB-INF
", create a sub-sub-directory "classes
" (case sensitive, plural) (i.e., "\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 should 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:
...... xxxxx INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [xxx\webapps\hello] xxxxx INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [xxx\webapps\hello] has finished in [38] ms ......
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 "
", 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".
Step 5(b) Write a Welcome Page
Create the following HTML page and save as "HelloHome.html
" in your webapp's root directory "hello
".
1 2 3 4 5 6 |
|
You can browse this page by issuing this URL:
http://localhost:9999/hello/HelloHome.html
Alternatively, you can issue an URL to your webapp's root "hello
":
http://localhost:9999/hello
The server will return the directory listing of your base directory. You can then click on "HelloHome.html
".
Rename "HelloHome.html
" to "index.html
", and issue a directory request again:
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.
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 does not block your access. You can use command such as "ipconfig
" (Windows), "ifconfig
" (Mac OS X 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.
2.7 STEP 6: Write a "Hello-world" Java Servlet
A servlet is Java program that runs inside a Java-capable HTTP Server, such as Apache Tomcat. A web user invokes a servlet by issuing an appropriate URL from a web browser (HTTP client).
Before you proceed, I shall assume that you are familiar with Java Programming and have installed the followings:
Step 6(a) Write a "Hello-world" Java Servlet
A Java servlet is a Java program that runs inside a HTTP server. A web user invokes a servlet by issuing a URL from a browser (or HTTP client).
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:
Write the following source codes called "HelloServlet.java
" and save it under your application "classes
" directory (i.e., "
"). This servlet says "Hello", echoes some request information, and prints a random number upon each request.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// To save as " |
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
.
Step 6(b) Compiling the Servlet (DIFFICULT)
We need the Java Servlet API to compile the servlet. Servlet API is NOT part of JDK. Tomcat provides a copy in
. We need to include this JAR file in the compilation via the -cp
(classpath) option as follows:
(For Windows)
// Assume that Tomcat is installed in c:\myWebProject\tomcat // Change directory to the Java source directory c: cd \myWebProject\tomcat\webapps\hello\WEB-INF\classes // Compile javac -cp .;c:\myWebProject\tomcat\lib\servlet-api.jar HelloServlet.java
(For Mac OS)
// Assume that Tomcat is installed in ~/myWebProject/tomcat // Change directory to the Java source directory cd ~/myWebProject/tomcat/webapps/hello/WEB-INF/classes // Compile - Need to use $HOME instead of ~ in the "javac" command javac -cp .:$HOME/myWebProject/tomcat/lib/servlet-api.jar HelloServlet.java
The output of the compilation is "HelloServlet.class
".
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.
Step 6(c) Invoke the Servlet
Restart your Tomcat Server (just in case ...).
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.
View Page Source
(For Firefox and Chrome) Right-click the page ⇒ "View Page Source" to look at the output received by the web browser (which is returned by the server). Take note that the web browser receives only the output of the servlet (generated via the out.println()
statements). The client has no access to the servlet source codes (which may contain confidential information).
(For Mac OS's Safari browser) You need to enable "Developer Menu" under the "Preferences" to enable the "View Source" menu.
Hello, World Hello, world!
Request URI: /hello/sayhello
Protocol: HTTP/1.1
PathInfo: null
Remote Address: 127.0.0.1
A Random Number: 0.3523682325749493
(Skip Unless...) The likely errors are "404 File Not Found" and "500 Internal Server Error". Read "How to debug" Section.
(Optional) Inspecting HTTP Request and Response Messages
When you enter a URL (e.g., http://localhost:9999/hello/sayhello
) on a web browser, an HTTP GET request message is sent to the server; and the server returns a response message for display on the web browser. You can inspect the request and response messages via Web browser's Developer Tool.
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). Enable "Net" (not in Gray). 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.
The request message header is as follows:
GET http://localhost:9999/hello/sayhello HTTP/1.1 Host: localhost:9999 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.5 Cache-Control:max-age=0 Connection: keep-alive Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
For this request, there is no request message body.
The response message header is as follows:
HTTP/1.1 200 OK Date: xxx, xx xxx xxxx xx:xx:xx xxx Content-Length: 286 Content-Type: text/html;charset=ISO-8859-1
The response message body is as follows:
Hello, World Hello, world!
Request URI: /hello/sayhello
Protocol: HTTP/1.1
PathInfo: null
Remote Address: 0:0:0:0:0:0:0:1
A Random Number: 0.4480280769255568
2.8 STEP 7: Write a Database Servlet
This section assumes that you are familiar with "Java database programming" and "MySQL database server". Otherwise, read "Java Database Program" and "How to Install MySQL and Get Started", respectively.
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
.
// For Windows: I shall assume that MySQL is installed in "c:\myWebProject\mysql" c: cd \myWebProject\mysql\bin mysqld --console // For Mac OS // Use graphical control at "System Preferences" -> MySQL
Start a MySQL client. I shall assume that there is a user called "myuser
" with password "xxxx
".
// For Windows: I shall assume that MySQL is installed in "c:\myWebProject\mysql" c: cd \myWebProject\mysql\bin mysql -u myuser -p // For Mac OS: I shall assume that MySQL is installed in "/usr/local/mysql" 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
.
create database if not exists ebookshop; use ebookshop; drop table if exists books; create table books ( id int, title varchar(50), author varchar(50), price float, qty int, primary key (id)); 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); select * from books;
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 Drive to Tomcat's "lib" (IMPORTANT!!!)
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
" (Mac OS).
Step 7(d) Write a Client-side HTML Form
Let's write an HTML script to create a query form with 3 checkboxes and a submit button, as illustrated below. Save the HTML file as “querybook.html
” in your application root directory “
”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
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
The URL request consists of two part: a URL corresponding to the "action
" attribute of the tag, and the "name=value" pair extracted from the
tag, separated by a
'?'
. Take note that blanks are replaced by '+'
(or %20
), because blanks are not allowed in the URL.
If you check two boxes (e.g., "Tan Ah Teck" and "Mohammad Ali"), you will get this URL, which has two "name=value" pairs separated by an '&'
.
http://localhost:9999/hello/query?author=Tan+Ah+Teck&author=Mohammad+Ali
Step 7(e) Write the Server-side Database Query Servlet
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
// To save as " |
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 tag of the "
querybook.html
" written earlier.
Compile "QueryServlet.java
" as follows:
// Windows c: // Change drive cd \myWebProject\tomcat\webapps\hello\WEB-INF\classes // Change directory to Java Source directory javac -cp .;c:\myWebProject\tomcat\lib\servlet-api.jar QueryServlet.java // Compile // Mac OS X cd ~/myWebProject/tomcat/webapps/hello/WEB-INF/classes // Change directory to Java Source directory javac -cp .:$HOME/myWebProject/tomcat/lib/servlet-api.jar QueryServlet.java // Compile
Use a "File Explorer", verify that "QueryServlet.class
" was generated in the "classes
" directory.
Step 7(f) Invoke the Servlet from the Client-Side Form
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 's "
action
" attribute, together with the name=value pair:
http://localhost:9999/hello/query?author=Tan+Ah+Teck
This URL "/query
" triggers QueryServlet
. The QueryServlet
retrieves the name=value pair of "author=Tan+Ah+Teck
". Inside the QueryServlet
, the method request.getParameter("author")
returns "Tan Ah Teck
", which is inserted into the SQL SELECT
command to query the database. The processed query result is then written to the client as an HTML document.
(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.
2.9 (Archive)(Prior to Tomcat 7) Deploying Servlets using web.xml
Please skip this section. I keep it here just in case...
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., "
").
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
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
".
Restart your Tomcat server to refresh the "web.xml
" file.
Note: For EACH servlet, you need to write a pair of
and
elements with a common but arbitrary
. Take note that all the
elements MUST be grouped together and placed IN FRONT of the
elements.
source: http://www.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html