Use Ant and Tomcat to create Web application _ MySQL

Source: Internet
Author: User
What technology is used? I use Tomcat 4's ServletJPS container technology to implement a Web application. There are still many uncertainties in this process. it is not easy to choose one of the multiple feasible technologies. In this article, I chose a solution that is as simple as possible and used in combination with assumerverpages (JSPs) and Java. Avoid using JSPs for Tomcat whenever possible



Technology used

I use Tomcat 4 Servlet/JPS container technology to implement a Web application. There are still many uncertainties in this process. it is not easy to choose one of the multiple feasible technologies. In this article, I chose a solution that is as simple as possible, using Java Server Pages (JSPs) and Java together.

Avoid using JSPs to implement complex logic as much as possible; that program may be easy to write, but difficult to debug and almost impossible to understand and maintain. A good solution is to use JSPs to display web pages (which JSPs are good at) and hand over the implementation of complex logic to Java, such as database access. In this way, the program is not only easy to implement and debug, but also easy to understand and maintain.

This Web application can run on a dedicated Web server or a PC. the operating system can be Windows, Linux, or Mac OS. The required software packages include the Java Runtime Environment (JDK 1.4 or later), the latest Tomcat version (Tomacat 4 or later), and Ant development tool (Ant or later ). Ant is used to create a Web application package (WAR), install and deploy the WAR file on Tomcat, and configure the relational database interface javax. SQL. DataSource. All the software packages mentioned above can be obtained free of charge through the Internet.


This Web application also needs a database. Almost all relational databases that support SQL and have JDBC drivers can. MySQL is a good choice. Obtain the latest MySQL version and its JDBC driver Connector/J from MySQL.com.

To make Ant and Tomact management software work together, you need to copy the catalina-ant.jar from the Tomcat server/lib directory to the Ant lib directory. Copy the JDBC driver of your database to the common/lib directory of Tomcat so that Tomcat and its Web applications can access the database. Finally, you must create Tomcat admin and manager roles (roles), and their usernames and passwords, edit the Tomcat conf directory under the tomcat-user.xml file is as follows:



My development environment is Apple Cube, which runs the Mac OS X 10.2.1 operating system, the software package JDK 1.3.1, Tomcat 4.1.12, Ant1.5.1, MySQL 3.23.52, and Connector/J 3.0.1-beta. No problem occurred when upgrading the operating system to Mac OS X 10.2.2. Similarly, no problem occurs when Tomcat is upgraded to 4.1.17.

Web applications

This article uses a simple address book program called AddressBook to explain how to apply the technology to be introduced. The purpose of this application is not to create an official version of the address book. it is just an example.

Java program in AddressBook: AddressBook contains three Java programs. Shows how they are used in Tomcat.







Home. jsp: Home. jsp is the Home page of AddressBook, which is the first page you see when using AddressBook. It uses a table to display all addresses in the Address Library. Each row in the table displays an address and deletes or modifies the connection of the address. There is a connection to add a new address at the bottom of the page. For configuration information, see web. xml notes.

Add the address connection and grant the control to RequestAdd. jsp.

Delete the address connection and grant the control to RequestDelete. jsp. the address id to be deleted is passed to this page.

Modify the address connection to grant control to RequestModify. jsp, and pass the address id to be modified to this page

For details, see the complete source code with comments in Home. jsp.

RequestAdd. jsp: RequestAdd. jsp provides an address form for entering a new address. You can cancel this operation by canceling the connection at the bottom of the page.

Submit the form and hand over the new address field value and control to DoAdd. jsp.

Cancel the operation and grant the control to Home. jsp. For details, see the complete and annotated source code of RequestAdd. jsp.

DoAdd. jsp: DoAdd. jsp displays the received address field value. Add the new address to the database and check whether the address is successful. There is a continuous connection at the bottom of the page.

Click "continue connection" to return to Home. jsp. For details, see the complete DoAdd. jsp source code with comments.

RequestDelete. jsp: address corresponding to the id obtained by RequestDelete. jsp. This page displays the address field in the table so that you can confirm that the correct address is deleted. The two connections at the bottom of the page are the continued connection of the request and the canceled connection of the request.

Select continue connection to go to DoDelete. jsp and pass the address id to be deleted

Select cancel connection to return to Home. jsp. For details, see the complete source code with annotations in RequestDelete. jsp.

DoDelete. jsp: the id passed to DoDelete. jsp for reading. The address corresponding to the id is displayed in the table. delete the id from the database and check whether it is successful. The connection continues at the bottom of the page.

Select continue to connect back to Home. jsp. For details, see the complete DoDelete. jsp source code with comments.

RequestModify. jsp: RequestModify. jsp displays a form and fills in the current address. It also provides the submit button and cancel the connection.

Submit the form to give the new address field value and control to DoModify. jsp.

Select cancel connection to return to Home. jsp. For details, see the complete and annotated source code of RequestModify. jsp.

DoModify. jsp: DoModify. jsp displays the received modified address field value. Modify the address record in the database and return whether the record is successful or not. The connection continues at the bottom of the page.

Select continue to connect back to Home. jsp. For details, see the complete DoModify. jsp source code with comments.

AddressBook Addresses database table: How to create a database depends on the database software used. If you are not using MySQL, modify the following steps as needed. AddressBook has only one Addresses table, which is stored in the Public database. Table ses sses has seven fields:

Id, primary key, automatically increasing data fields

Surname, a 24-character domain, stores the contact's surname

Firstname, a 24-character domain, stores the contact name

Street, which is a string of 80 characters and stores the first line of the address.

District, which is a string of 80 characters and stores the second line of the address.

City, 40 characters in length, save the city name

Postcode, which is a 10-character domain and saves the ZIP code

First, create a MySQL database (Mac OS X 10.2.1 ). Start the mysql command line tool with the administrator privilege. enter the password if necessary. Create a Public database and mysqlusername and password mysqlpassord. The command is as follows:

# Mysql-u root-pmysql> create database Public; mysql> grant all privileges on Public. * to mysqlusername @ localhostidentified by 'mysqlpassword' with grant option; mysql> flush privileges;



Then, create the Addresses table in the Public database.

Mysql> create table Addresses (id int (8) primary key auto_increment, surname varchar (24) not null, firstname varchar (24) not null, street varchar (80) not null, district varchar (80) not null, city varchar (40) not null, postcode varchar (10) not null );



Use the command Commit; submit. To check whether the operation on the table is correct, enter the describe Addresser command. the following result is displayed:

+ ----------- + ------------- + ------ + ----- + --------- + ---------------- + | Field | Type | Null | Key | Default | Extra | + ----------- + ------------- + ------ + ----------- + ---------------- + | id | int (8) | PRI | NULL | auto_increment | surname | varchar (24) | firstname | varchar (24) | street | varchar (80) | district | varchar (80) | city | varchar (40) | postcode | varchar (10) | + ----------- + ------------- + ------ + ----- + --------- + ---------------- +



Now you can insert a row to test the database.

Mysql> insert into Addresses (surname, firstname, street, district, city, postcode) values ("Smith", "John", "1, The High Street,", "Downtown, "," Metropolis. "," X99 9XX "); mysql> commit; mysql> select * from Addresses;



The result is as follows:




Note that the address id is automatically assigned a value of 1. So far, the database of AddressesBook has been created.

Configure the development directory of AddresBook

Now we configure the directory to store the AddressBook source file and the war Directory of the Web application, which is also the directory to store the Web application package. Download the AddressBook source code package. After decompression, the Ant program directory structure can be obtained, as shown in 3. Do you need to make special changes to the development directory of AddressBook? We recommend that you extract it to your home directory (Mac OS ).


Let's take a look at these files:

AddressBook/build. properties: AddressBook/build. properties contains a number of settings read by AddressBook/build. xml. During the build process, try to edit a small build. properties file instead of modifying complicated build. xml files.

App. name = AddressBooktomcat. home =/usr/local/jakarta-tomcat-4.1.12manager.url = http: // localhost: 8080/managerusername = atatusernamepassword = tomcatpassword



The app. name parameter does not need to be modified. If you want to reuse these files to create a new Web application, change the parameter to the new program name. If Tomcat 4 is run on the local machine, you do not need to modify the manager. url parameter.

The tomcat. home parameter is the installation directory of Tomcat. the preceding settings indicate that Tomcat 4.1.12 is installed in the/url/local directory (Mac OS ). Ant will set the CLASSPATH variable for AddressBook compilation based on this parameter so that it contains the Tomcat common/lib. jar file. (So Tomcat and Web applications can directly access this file without having to copy it to the application's WEB-INF/lib directory .)

Tomcat also has a similar Directory: shared/lib. the. jar file under the Directory is accessible to the application at runtime, but not Tomcat.

The tomcatusrename and tomcatpassword parameters must be consistent with the settings in the configuration file conf/tomcat-users.xml of Tomcat. Ant uses them and manager. url to obtain the permission to install the AddressBook application in the Tomcat environment.

For details, see the complete source code with comments of build. properties.

AddressBook/build. xml: the AddressBook/build. xml file is the Ant configuration file, which uses many Ant labels. The following are commonly used:

? Ant build

? Ant install Web application for testing

? Ant remove uninstall Web applications

? Ant deploy install and deploy Web applications

? Ant undeploy uninstall Web applications

For details, see the complete source code with comments in build. xml.

AddressBook/context. xml: AddressBook/context. xml is included in Tomcat when Ant processes installation, reload, deletion, deployment, and uninstallation requests. The file records the context information of AddressBook, or the parameters required for Tomcat to run AddressBook.

The Logger item defines the event logs of AddressBook recorded by Tomcat in text format and stored in the logs directory of Tomcat. Define the log file named localhost_addressbook_log.yyyy-mm-dd.txt with the YYYY-MM-DD as the log date:





Resource and ResourceParams define that Tomcat must create a javax. SQL. DataSource called jdbc/Publicd for AddressBook. The following configuration creates a javax. SQL. DataSource with the value org. apache. commons. dbcp. BasicDataSourceFactory class. the URL is jdbc: mysql: // localhost: 3306/Public? AutoReconnect = true, JDBC Driver: org. gjt. mm. mysql. Driver. the username and password are mysqlusername and mysqlpassword:

The above code uses javax. SQL. DataSource as the context variable of the Web application. If this variable is used by more than one Web application, you can define it as a global resource. For details, see the complete source code with annotations in context. xml.

AddressBook/src/*. java: three Java programs for Web applications are stored in the src directory. See the description of Address. java, AddressesDB. java and ContextListener. java.

AddressBook/web/*. jsp: the web Directory stores seven JSP pages of Web applications. See the Home. jsp, RequestAdd. jsp, DoAdd. jsp, RequestDelete. jsp, DoDelete. jsp, RequestModify. jsp, and DoModify. jsp descriptions.

AddressBook/web/WEB-INF/web. xml: AddressBook/web/WEB-INF/web. xml is the web application deployment description file for AddressBook. The listener parameter defines the Java listener AddressBook. ContextListener, which is called when the program is started or closed.

AddressBook. ContextListener



The welcom-file-list parameter defines the AddressBook homepage. The following settings define the Home page of AddressBook as Home. jsp.

Home. jsp



For details, see the complete web. xml source code with comments.

Create, install, deploy, and run AddressBook: to install AddressBook, first change the current directory to the AddressBook directory, and then run the Ant install command:

$ Cd AddressBook $ ant install



If the installation fails, check whether the tomcat-user.xml under the conf directory of Tomcat is correctly configured and whether the catalina-ant.jar is copied from the server/lib directory of Tomcat to the lib directory of Ant.

Note that ant install automatically triggers the running of several Ant labels, namely, ant int, ant prepare, ant build, and ant package:

? Ant init initialization timestamp

? Ant prepare creates a war directory structure under the AddressBook Directory, including a war Directory, a war/WAR-INF Directory, a war/WEB-INF/classes directory, and a war/WEB-INF/lib directory.

? Ant build creates a Web application, including copying jsp files to the war directory and. copy the xml file to the war/META-INF directory and. copy the xml file to the war/WEB-INF directory, and compile the Java file results into the war/WEB-INF/classes directory.

? The ant package creates a Web package from the war directory. The Web package is a. jar file created by the jar tool.

? Finally, ant install installs the Web package to Tomcat based on the war/META-INF/context. xml configuration information. You may notice that you can install AddressBook without logging on to the root account or Tomcat, as long as you have a common user account. Ant can safely perform the above process by defining tomcatusername and tomcatpassword in AddressBook/build. properties.

The installation process varies depending on the configuration options. for details about the configuration information, see AddressBook/build. xml. Displays the war directory structure and various files that constitute the AddressBook Web application.




Enter http: // localhost: 8080/AddressBook in the address bar of the browser to test the AddressBook program. Expected result 5 is displayed. If the application is not running correctly, check whether the JDBC driver of the database is in the common/lib directory of Tomcat. If the application with the correct database driver still does not run properly, check the log files in the Tomcat log Directory. these text-format log files will help you find errors.


Add an address, modify it, delete it, and add an address. You will see that the id continues to automatically increase.

Development process

After AddressBook is successfully installed, Tomcat calls AddressBook. ConextListener. contextInitialized to create an instance of AddressBook. AddressesDB. AddressBook. AddressesDB uses jdbc/Public DataSource to establish a database connection. AddressBook. ConextListener. contextInitialized saves the instance of AddressBook. AddressesDB as a servlet attribute (addressesDB.

When Home. jsp of AddressBook is called for the first time, Tomcat compiles and runs it. Home. jsp obtains the AddressBook. addressesDB instance through the servlet attribute AddressesDB, then reads the address from the database and displays it. When other JSP pages are used for the first time, they must be compiled before execution. the method for reading the database is the same as Home. jsp.

Ant stop is used to stop the AddressBook program. Tomcat automatically calls AddressBook. ContextListener. contextDestroyed to get the instance of the servlet attribute addressesDB and AddressBook. AddressesDB mentioned above, close the database connection, and delete the servlet attribute addressesDB.

Ant start is used to start the AddressBook program. Tomcat automatically calls AddressBook. ConextListener. contextInitialized to repeat the startup process.

The entire Web application development process is as follows: modify the program; use ant install to create and install; in the browser, type the address http: // localhost: 8080/applicationName (or click the refresh button) to test the Web application. use ant remove to delete the context information of the Web application. Repeat the process until debugging is completed. After the program has been debugged, use ant deploy to officially configure your program to the server. After restarting Tomcat or the server, your application starts to run. Use the ant undeploy command to completely delete Web applications from your server.

Tomcat Manager

Tomcat Manager can replace Ant. Enter http: // localhost: 8080/manager/html/list in the browser. the Tomcat Manager Web page shown in 6 is displayed.


Alternatively, directly use the following address:

Http: // localhost: 8080/manager/list

Http: // localhost: 8080/manager/resources

Http: // localhost: 8080/manager/roles

Http: // localhost: 8080/manager/start? Path =/AddressBook

Http: // localhost: 8080/manager/stop? Path =/AddressBook

Http: // localhost: 8080/manager/remove? Path =/AddressBook

Http: // localhost: 8080/manager/sessions? Path =/AddressBook

Tomcat Administrator

To log on to Tomcat's Web-based administrator, use the address http: // localhost: 8080/admin. Enter the username and password of the Tomcat "admin" role in the logon screen. the username and password of the Tomcat "admin" role are the same as those of the "manager" role. The Tomcat-users.xml file is admin, and the manager and provider roles create the same account. Creating different accounts for each Tomcat role is unnecessary.

The control page consists of three panels: the header panel, the tree panel, and the data panel. 7:




Tree branches can be expanded and selected. Expand Service {Tomcat-Standalone}-> Host {localhost}-> Context {/AddressBook} in sequence, and finally the Resource branch of AddressBook. Do not confuse the global Resource branch at the bottom of the tree with the Resource branch of AddressBook. The global Resource branch can be used to define global resources available for any Web application.

AddressBook context panel

Select the Context {/AddressBook} branch and you will see the Context panel of AddressBook (8 ).




You can change the panel parameters at will, mainly three different Debug Level parameters. To Save settings, click Save and then click Commit Changes in the header panel.

Data Source panel of AddressBook

Select the Data Source branch in the Resource branch of Context {/AddressBook}. you will see the Data Source panel of AddressBook. Select the data source jdbc/Public to display javax. SQL. DataSource (9 ).





You can change the parameters of the panel at will, including Data Source URL, JDBC Driver Class, User Name, Password, Max. Active Connections, Max. Idle Connections, and Max. Wait for Connection. To Save settings, click Save and then click Commit Changes in the header panel.

It may not matter if you run Web applications on your PC, but it is important if you are running Web servers as a company product. These parameters can be safely changed, and not only can be changed by programmers, but also by Tomcat administrator. As a programmer, I have to remember many accounts and passwords. I don't want to know the account and password of the company's product database. This account and password are necessary, but with the administrator service of javax. SQL. DataSource and Tomcat 4, I don't have to know them.

Ant is used to establish the Web application context during software development, while Tomcat administrator is used in the product environment.

AddressBook log panel

Select the Logger for Context {/AddressBook} branch of the Context {/AddressBook} branch in the tree. the log panel of AddressBook 10 is displayed.




You can change the panel parameters at will, mainly Debug Level and Verbosity Level parameters. To Save settings, click Save and then click Commit Changes in the header panel.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.