Creating Web applications using Ant and Tomcat

Source: Internet
Author: User
Tags functions header implement connect mysql one table variable mysql database
web| Create


what technology to use

I implemented a Web application using Tomcat 4 's SERVLET/JPS container technology. There are still a lot of uncertainties in this process, and it's not easy to choose one of several possible technologies. In this article, I chose the simplest possible solution, mixing Java Server Pages (JSPs) with Java.

You should try to avoid using JSPs to implement complex logic; 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 in charge of the display of Web pages (which is exactly what JSPs is good at), handing the implementation of complex logic to Java, such as access to the database. In this way, the program is not only easier to implement and debug, but also easy to understand and maintain.

This Web application can be run on a dedicated web server or on a personal computer, and the operating system can be windows,linux, or Mac OS. The required packages are the Java Runtime Environment (JDK1.2 or above), the latest version of Tomcat (Tomacat 4 or above), and the Ant development tool (Ant 1.4 or later). Ant is used to create a Web application Package (war) and to install the deployment WAR file on tomcat and configure the relational database interface Javax.sql.DataSource. All of the above mentioned packages are available free of charge over the Internet.

This web application also needs a database. Almost all of the relational databases that support SQL and have JDBC drivers are available. MySQL is a good choice to meet the requirements. From mysql.com you can get the latest version of MySQL and its JDBC-driven connector/j.

In order for Ant to work with tomact management software, you need to copy Catalina-ant.jar from Tomcat's Server/lib directory to Ant's lib directory. Copy your database JDBC driver to Tomcat's Common/lib directory so that the database can be accessed by Tomcat and the Web application on it. Finally, you must establish Tomcat's admin and manager roles (roles), with its username and password, and edit the Tomcat-user.xml files under Tomcat's Conf directory as follows:

ffffff cellpadding=2 width=540 align=center bordercolorlight=black border=1>

 
  
   
  <?xml version= ' 1.0 '?>    <tomcat-users>        <role rolename= "admin"/> <role rolename=        " Manager "/>        <user username=" Tomcatusername password= "Tomcatpassword" roles= "Admin,manager"/>    </tomcat-users>
 
  


My development environment is Apple Cube, run Mac OS X 10.2.1 operating system, package JDK 1.3.1,tomcat 4.1.12,ant1.5.1,mysql 3.23.52, and connector/j 3.0.1-beta. The operating system upgrade to Mac OS X 10.2.2 does not show any problems. Also, there was no problem with Tomcat upgrades to 4.1.17.

Web Application

This article uses a simple address book program called AddressBook to illustrate how to apply the technology that will 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. Figure 1 shows how they are used in Tomcat.





Addressbook.contextlistener: Addressbook.contextlistener is a servlet context listener that is invoked when AddressBook starts and closes, and can be configured using AddressBook deployment Profile Web.xml. When the addressbook begins to run, create an instance of Addressesdb and save it as a context property, and when the AddressBook run is finished, remove the Addressesdb object from the context property and close the database connection. During the run, when JSPs needs to connect to the database, they will access the Addressesdb object in the context property. For details, see Contextlistener.java's Full annotated source code.

AddressBook. Addressesdb: AddressBook. Addressesdb is used to manipulate the address database. Its constructor establishes a database connection that can be shared by multiple Web sessions. This class provides multiple database connection functions:

GetAddress (ID) returns the address identified with the ID and returns NULL if the address is not found.

AddAddress add address and return the number of rows changed

Deleteaddress (ID) deletes the address and returns the number of rows changed

GetAddresses () returns the aggregation of all addresses in the database if the database is invalid returns null

Close () Closes the database connection

For details, see Addressesdb.java's Full annotated source code.

AddressBook. Address: AddressBook. Address is the class used to describe addresses. When programming with JSPs, it is still a good idea to use a class set to describe the data. This is the method used in AddressBook. AddressBook. The constructor of the address saves the content of addresses in the object. This class includes a normal get function that takes a single address field, two get functions that obtain the merged address field, and an address comparison function:

Address (Id,surname,fisrtname,street,district,city,postcode)

GetId ()

Getsurname ()

Getfirstname ()

Getstreet ()

Getdistrict ()

Getcity ()

Getpostcode ()

Getfullname () Return to firstname+ "" +surname

Getfulladdress () Return to street+ "" +district+ "" +city+ "" +postcode

CompareTo (address) returns negative integers, 0, positive integers, respectively corresponding to surname and FirstName greater than, equal to, less than this surname and FirstName, compared to case insensitive. Used when storing address aggregation.

For details, see Address.java's full, annotated source code.

jsp page in AddressBook: AddressBook has seven JSP pages. Each represents a Web page that operates independently of the AddressBook database. The status of each page database is independent of the state of the previous page database. If the database is changed by another user, the Web page detects and produces the appropriate action. For example, if you are modifying an address and another user deletes the address before confirming the modification, the JSP notifies you that the modification of the Non-existent address failed.

Figure 2 shows the logical relationship between JSPs.





home.jsp: Home.jsp is the homepage of addressbook, the first page that users see when they use AddressBook. It uses a table to display all the addresses in the address library. Each row in the table displays an address, as well as a connection to delete or modify the address. There is a connection at the bottom of the page that adds a new address. Configuration information see Web.xml notes.

Add address connection give control to requestadd.jsp

Deleting an address connection gives control to requestdelete.jsp and passes the address ID you want to delete to the page

Modifying an address connection gives control to requestmodify.jsp and passes the address ID that will be modified to the page

For details, see Home.jsp's Full annotated source code.

requestadd.jsp: requestadd.jsp provides an address form for entering a new address. Cancel the connection at the bottom of the page to cancel this operation.

Submit form to the new Address field value and control to doadd.jsp

Canceling the operation gives control to home.jsp. For details, see Requestadd.jsp's full, annotated source code.

doadd.jsp: doadd.jsp Displays the value of the Address field received. The new address is then added to the database and the information is displayed for success. There is a continued connection at the bottom of the page.

Click Continue to connect back to home.jsp. For details, see Doadd.jsp's full, annotated source code.

requestdelete.jsp: requestdelete.jsp read the corresponding address of the ID. The page displays the Address field in the table so that you can confirm that the correct address is being deleted. The two connections at the bottom of the page are the continuation of the requested connection and the cancellation of the requested cancel connection.

Select Continue connection will go to dodelete.jsp and pass the address ID to be deleted

Choose to cancel the connection back to home.jsp. For details, see Requestdelete.jsp's Full annotated source code.

dodelete.jsp: dodelete.jsp reads the ID passed to it. Displays the address of the ID in the table, deletes it from the database, and displays whether it was successful. The bottom of the page is to continue the connection.

Choose to continue connecting back to home.jsp. For details, see Dodelete.jsp's full, annotated source code.

requestmodify.jsp: requestmodify.jsp displays a form and fills in the current address, providing the submit button and canceling the connection.

Submit form to the new Address field value and control to domodify.jsp

Choose to cancel the connection back to home.jsp. For details, see Requestmodify.jsp's full, annotated source code.

domodify.jsp: domodify.jsp Displays the modified address field values that were received. It then modifies the address records in the database and returns success or failure. The bottom of the page is to continue the connection.

Choose to continue connecting back to home.jsp. For details, see Domodify.jsp's full, annotated source code.

AddressBook's Addresses database table: How to build a database depends on the database software used. If you're not using MySQL, the following steps need to be modified according to the circumstances. AddressBook has only one table addresses, which is saved in the database public. Table addresses has seven domains:

IDS, primary keys, automatically growing data fields

Surname, with a length of 24 characters Value field, save the last name of the contact person

FirstName, with a length of 24 characters Value field, save the name of the contact person

Street, with a length of 80 characters Value field, save the first line of address

District, with a length of 80 characters Value field, save the second line of the address

City, with a length of 40 characters Value field, save the town name

Postcode, 10-Length character value field, save zip code

First set up MySQL database (Mac OS X 10.2.1). Start the MySQL command-line tool with administrator privileges and enter a password if necessary. Create public database, and account mysqlusername password Mysqlpassord. The order is as follows:

 
   
    
  # mysql-u root-pmysql> CREATE DATABASE public;mysql> grant all privileges in public.* to Mysqlusername@localhostid Entified 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 () NOT NULL, FirstName V  Archar is not NULL, the street varchar is not NULL, district varchar is not NULL, and city varchar is not      null, Postcode  varchar (a) not null);
 
    


To commit with an order; To check if the action on the table is correct, type the command describe Addresser, and you will get the following result:

 
     
      
  +-----------+-------------+------+-----+---------+----------------+| Field      | Type          | Null | Key | Default | Extra       |+-----------+-------------+------+-----+---------+----------------+| ID          | int (8)       |       | PRI | NULL |auto_increment| | surname | varchar | | | | |              firstname | varchar       | |      |         |              || Street     | varchar | | | | | | | | | | | | | | |              City        | varchar | | | | | | | | | | | | |              +-----------+-------------+------+-----+---------+----------------+
 
     


You can now insert a row to test the database

 
      
       
  mysql> insert into Addresses (surname, FirstName, Street, district,city, postcode) VALUES ("Smith", "John", "1, the Hig H Street, "," Downtown, "," Metropolis. "," X99 9XX ");mysql> commit;mysql> select * from Addresses;
 
      


The results are as follows:





Note that the ID of the address is automatically assigned a value of 1. The database creation for this addressesbook is complete.

Configure the Addresbook development directory

Now we configure the directory where the addressbook source files are stored, and the Web application's war directory, which is also the directory where the Web application packages are stored. Download AddressBook source program compression package. After decompression, you will get the source directory structure that ant can process, as shown in Figure 3. There is no need to make a special change to the AddressBook development directory-it is recommended 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 Addressbook/build.xml read access settings information. When customizing the build process, try to edit the smaller build.properties files, rather than modifying the more complex build.xml files.

 
       
        
  app.name=addressbooktomcat.home=/usr/local/jakarta-tomcat-4.1.12manager.url=http://localhost:8080/ Managerusername=tomcatusernamepassword=tomcatpassword
 
       


The App.name parameter does not need to be modified. If you want to reuse these files in the future to create a new Web application, change the parameter to a new program name. If you run Tomcat 4 on the local machine, the Manager.url parameter does not have to be modified.

The Tomcat.home parameter is a Tomcat installation directory, and the above setting indicates that the Tomcat 4.1.12 is installed in the/url/local directory (Mac OS). Based on this parameter, ant sets the classpath variable to compile addressbook, which contains the Tomcat Common/lib.jar file. (This allows both Tomcat and Web applications to access the file directly, 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 run time, but is not accessible to Tomcat.

The parameters Tomcatusrename and Tomcatpassword must be consistent with the settings in Tomcat's configuration file conf/tomcat-users.xml. Ant uses them and manager.url to get permission to install AddressBook applications in a tomcat environment.

For details, see Build.properties's Full annotated source code.

Addressbook/build.xml: The Addressbook/build.xml file is an ant configuration file that uses a number of ant tags. The following are the more commonly used:

· Ant build creates a Web application

· Ant install installation Web application for testing

· Ant Remove Uninstall Web application

· Ant deploy installation Deployment Web application

· Ant undeploy Uninstall Web application

For details, see Build.xml's Full annotated source code.

Addressbook/context.xml: Addressbook/context.xml is in the ant process installation, reload, delete, deploy, uninstall request fashion into Tomcat. The AddressBook context information is recorded for the file, or the parameters required for Tomcat to run AddressBook.

The logger item defines that Tomcat records AddressBook event logs in text format and is stored in Tomcat's logs directory. The following logger item defines the name Localhost_addressbook_log. Yyyy-mm-dd.txt log file, where Yyyy-mm-dd is the log date:

 
        
         
  <logger classname= "Org.apache.catalina.logger.FileLogger" prefix=  localhost_addressbook_log. "Suffix=". TXT "timestamp=" true "/>
 
        


The resource and Resourceparams entries define that Tomcat must create a javax.sql.DataSource called Jdbc/publicd for AddressBook. The following setting creates a javax.sql.DataSource whose value is Org.apache.commons.dbcp.BasicDataSourceFactory class and the URL is jdbc:mysql://localhost : 3306/public?autoreconnect=true,jdbc driver: org.gjt.mm.mysql.Driver, username and password respectively: Mysqlusername and Mysqlpassword:

The code above will javax.sql.DataSource as the context variable for the Web application. If the variable is not only used by a Web application, it can be defined as a global resource. For details, see Context.xml's Full annotated source code.

Addressbook/src/*.java: Three Java programs that store Web applications in the SRC directory. See the description of Address.java,addressesdb.java and Contextlistener.java.

addressbook/web/*.jsp: A Web directory that holds seven JSP pages for Web applications. See 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 a addressbook Web application deployment profile. It contains two main parameters: the Listener parameter defines the Java class Listener Addressbook.contextlistener, which is invoked when the program starts and closes.

 
         
          
  <listener>   <listener-class>AddressBook.ContextListener</listener-class></listener>
 
         


The Welcom-file-list parameter defines the first page of the addressbook. The following settings define AddressBook's home page as home.jsp.

 
          
           
  <welcome-file-list>   <welcome-file>Home.jsp</welcome-file></welcome-file-list>
 
          


For details, see Web.xml's full, annotated source code.

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

 
           
            
  $ cd addressbook$ ant install
 
           


If the installation fails, check to see if Tomcat-user.xml is configured correctly in Tomcat's Conf directory, and Catalina-ant.jar whether to copy from Tomcat's Server/lib directory to Ant's lib directory.

Note that ant install automatically triggers several tabs running ant, followed by the Ant int,ant prepare,ant build and Ant package:

· Ant init initialization timestamp

· Ant prepare creates a war directory structure in 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.

· The ant build creates a WEB application, including copying the JSP files into the war directory, copying the context.xml files to the War/meta-inf directory, and copying the web.xml files to the War/web-inf directory. and compile the Java file results into the war/web-inf/classes directory.

· Ant package creates a Web package from the war directory. A Web package is a. jar file created by the Jar tool.

· Finally, ant install installs the Web package into Tomcat based on the War/meta-inf/context.xml configuration information. You may notice that you do not need to log in root or tomcat can install addressbook, as long as your regular user account. Ant uses the tomcatusername and Tomcatpassword defined in Addressbook/build.properties to safely execute the above procedure.

The installation process differs depending on the configuration options, and the configuration information is addressbook/build.xml. Figure 4 shows the war directory structure and various files that make up the AddressBook Web application.





Enter the address Http://localhost:8080/AddressBook test AddressBook program in the browser address bar. You should get the results shown in Figure 5. If the application is not running correctly, check the Common/lib directory of Tomcat for any JDBC drivers for the database. If the database-driven correct application still does not run correctly, check the log files in Tomcat's log directory, which will help you find the error.





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

Development Process

After the AddressBook installation succeeds, Tomcat calls AddressBook.ConextListener.contextInitialized to create an instance of the Addressbook.addressesdb. ADDRESSBOOK.ADDRESSESDB establishes a database connection through the Jdbc/public datasource. AddressBook.ConextListener.contextInitialized saves the instance of Addressbook.addressesdb as a servlet property (ADDRESSESDB).

When AddressBook's home.jsp is invoked for the first time, Tomcat compiles and executes it. Home.jsp obtains an instance of Addressbook.addressesdb through the Servlet property Addressesdb and then reads the address from the database and displays it. Other JSP pages should be compiled and executed first when they are used, and the methods of reading the database are home.jsp.

Ant stop is used to stop the AddressBook program. Tomcat automatically invokes AddressBook.ContextListener.contextDestroyed to obtain an instance of the servlet attribute Addressesdb and Addressbook.addressesdb mentioned above, close the database connection and remove SE Rvlet Property Addressesdb.

Ant start is used to start the AddressBook program. Tomcat automatically invokes the AddressBook.ConextListener.contextInitialized repeat boot process.

The development process for the entire Web application is this: modifying the program, creating and installing with ant install, typing the address http://localhost:8080/applicationName (or clicking the Refresh button) in the browser to test the Web program; Remove the context information for the Web application, and repeat the entire process until debugging is complete. When the program has finished debugging, use ant deploy to formally configure your program to the server. After you restart Tomcat or reboot the server, your application starts running. To remove a Web application from your server completely, use the Ant undeploy command.

Tomcat Manager

Use Tomcat Manager to replace Ant. Typing address http://localhost:8080/manager/html/list in the browser will appear with the Tomcat Manager Web page as shown in Figure 6.





Alternatively, use the following address directly:

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 for the Tomcat "admin" role in the login screen, the same as Tomcatusername and Tomcatpassword, as in the "manager" role. The Tomcat-users.xml file establishes the same account for the Admin,manager and provider roles. It is not necessary to create a different account for each tomcat role.

The control page is divided into three panels: the head panel, the tree panel, and the Data panel. As shown in Figure 7:





Branches of the tree can be expanded and selected. Expand Service{tomcat-standalone}->host{localhost}->context{/addressbook in turn, and the resource branch of the last addressbook. Be careful not to confuse the global resource Branch at the bottom of the tree with the resource branch of the AddressBook. The global resource branch can be used to define global resources that are available to any Web application.

AddressBook Context Panel

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





You can change the panel's parameters at will, mainly three different debug level parameters. To save the settings click the Save button and then click the Commit Changes button in the header panel.

AddressBook's data source panel

Select the data source branch of the resource branch of Context{/addressbook} and you will see the AddressBook data source panel. Select the data source jdbc/public display Javax.sql.DataSource (Figure 9).





You can change the panel's parameters at will, including the data Source URL, JDBC Driver Class, User Name, Password, Max. Active connections, Max. Idle connections and Max. Wait for connection parameter. To save the settings click the Save button and then click the Commit Changes button in the header panel.

This may not be important if you are running a Web application on your PC, but this is important if you are a Web server for your company's products. These parameters can be changed securely, and not only programmers can change, but also Tomcat administrators can. As a programmer I have to remember a lot of accounts and passwords, I do not want to know the company's product database account and password. This account and password are necessary, but with the Javax.sql.DataSource and Tomcat 4 's administrator service, I don't need to know about them.

Ant is used to build the Web application context when developing software, while the Tomcat Administrator service is used in the product environment.

AddressBook's log panel

Select the logger for Context{/addressbook} branch of Context{/addressbook} in the tree to see the AddressBook log panel as shown in Figure 10





You can change the panel's parameters at will, mainly the debug level and verbosity level parameters. To save the settings click the Save button and then click the Commit Changes button in the header panel.




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.