Reproduced from: http://tech.it168.com/jd/2007-11-09/200711091344781.shtml
Ant is a Cross-platform component tool under the Apache Foundation, which enables the automatic construction and deployment of projects. In this article, the reader is primarily familiar with how to apply ant to a Java project to simplify build and deploy operations.
one. Installation and Configuration
Download Address: http://ant.apache.org/, downloaded in this article is version 1.7.0. Extract to a directory (for example, E: "apache-ant-1.7.0") to use.
Add system environment variable: Ant_home, which points to the root of ANT decompression, this is e: "apache-ant-1.7.0."
Once installed and configured, the reader can test whether ant is available, first into Ant's Bin directory, Run command ant–version, and if the installation and configuration succeeds, the ant version information is displayed, as shown in the following illustration:
As you can see, when the reader runs Ant's command, it needs to go into Ant's Bin directory and how to get the system to automatically find Ant. The reader is then required to add ant's Bin directory to the System environment variable path. Once the setup is complete, we can enter the ant command in any directory (such as the C: "Documents and Settings" Amigoxie directory) to get the result of the command running.
two. Ant's key element
Ant's widget files are written based on XML, and the default name is Build.xml. To get a better idea of ant, write a simple ant program here to show Ant's functionality and give the reader a rudimentary understanding of ant. First, create a build.xml file under E disk, which reads as follows:
<?xml version= "1.0"?>
<project name= "HelloWorld" >
<target name= "SayHelloWorld" >
<echo message= "Hello,amigo"/>
</target>
</project>
The reader can go to e disk and run Ant SayHelloWorld to see the following results:
D:\>ant SayHelloWorld
Buildfile:build.xml
SayHelloWorld:
[Echo] Hello,amigo
Build successful
Total time:0 seconds
Where SayHelloWorld is the name of the task that needs to be performed. If the file name is not Build.xml and is hello.xml, when the reader runs the same command, the following error occurs in the command window:
Buildfile:build.xml does not exist!
Build failed
The error prompted by the above command shows that the ant command is looking for the Build.xml file by default. If the file name is Hello.xml, the reader will also need to make a slight change to the order, instead: Ant–f hello.xml sayhelloworld, ant–buildfile hello.xml SayHelloWorld or Ant–file Hello.xml SayHelloWorld.
Let's begin by explaining the focus of this section to your audience: key elements of Ant project, target, property, and task.
1. Project Elements
The project element is the root element of the ant widget file, and the ant widget file should contain at least one project element, or an error will occur. Under each project element, you can include multiple target elements. Next, show the reader the properties of the project element.
1) Name Property
Use to specify the name of a project element.
2) Default property
Specifies the name of the target to execute when project defaults.
3) Basedir Property
is used to specify the location of the base path. When this property is not specified, use the attached directory of ant's widget file as the base directory.
Here's a simple example to illustrate the use of project elements. Modify e: "Build.xml file, the revised content is as follows:
<?xml version= "1.0"?> <project name= "Projectstudy" default=
"Saybasedir" basedir= "E:" apache-ant-1.7.0 " >
<target name= "Saybasedir" >
<echo message= "The base dir is: ${basedir}"/>
</target >
</project>
As we can see from the above, the value of the default property is defined here as Saybasedir, that is, when the ant command is run, the target saybasedir is executed by default when the target is executed, and the value of the Basedir property is also defined as E : "apache-ant-1.7.0, run the ant command after entering e disk, and you can see the results of the run, as shown in the following illustration:
D:\>ant
Buildfile:build.xml
Saybasedir:
[Echo] The Base dir is:c:\ant_home\apache-ant-1.7.0
Build successful
Total time:0 seconds
-------------------------------------
D:\>ant
Buildfile:build.xml
Saybasedir:
[Echo] The Base dir is:d:\
Build successful
Total time:0 seconds
Because the value of the Basedir is set, the value of the Basedir property becomes the value that the reader sets. The reader can remove the Basedir attribute of the project element and then run ant to see the results, at which point the Basedir value becomes E: "The parent directory of the ant component file."
Sometimes, readers may have the need to get all the target names under a project, and the reader can do that by adding-proecthelp to the ant command. For example, we run Ant–projecthelp for the above example, and the output is as follows:
Buildfile:build.xml
Main Targets:
Other targets:
Saybasedir
Default Target:saybasedir
2. Target element
It is the basic execution unit of ant, which can contain one or more specific tasks. Multiple target can have interdependencies. It has the following properties:
1) Name Property
Specifies the name of the target element, which is unique within a project element. We can specify a target by specifying the name of the target element.
2) Depends property
Used to describe the dependencies between target and if there is a dependency on multiple target, the "," interval is required. Ant executes each target sequentially according to the order in which target appears in the depends attribute. The target being relied on will execute first.
3) If property
Used to verify that the specified property exists, and if it does not exist, Target will not be executed.
4) Unless property
The function of this property is the opposite of the function of the If property, and it is also used to verify that the specified property exists, and if it does not exist, the target will be executed.
5) Description Property
This property is a short description and description of the target feature.
Here's a guide to the reader to see an example of a comprehensive use of each attribute. Modify e: "Build.xml file, the revised content is as follows:
<?xml version= "1.0"?> <project name= "Targetstudy"
>
<target name= "Targeta" Ant.java.version ">
<echo message=" Java version: ${ant.java.version} "/>
</target>
< Target Name= "Targetb" depends= "Targeta" unless= "amigo" >
<description>
a depend example!
</description>
<echo message= "The base dir is: ${basedir}"/>
</target>
</project >
When you run Ant Targetb after entering e disk, you can see the results of the operation as shown in the following illustration:
D:\>ant Target
Buildfile:build.xml
Targeta:
[Echo] Java version:1.6
TARGETB:
[Echo] The Base dir is:d:\
Build successful
Total time:0 seconds
When the reader analyzes the results, we can see that we are running target named Targetb, which relies on Targeta, so Targeta will be executed first, and because the system has a Java environment installed, So the Ant.java.version property exists and executes the target of Targeta, output information: [echo] Java Version:1.5,targeta after execution, then executes TARGETB, because Amigo does not exist, The unless attribute is entered at Target when it does not exist, so that TARGETB can execute and output information: the base dir is:e: ".
3. Property element
This element can be considered as a parameter or argument definition, and project properties can be set by the property element or outside of ant. To introduce a file externally, such as a build.properties file, you can introduce it through the following: <property file= "Build.properties"/>
Property elements can be used as attribute values for a task. The task is implemented by placing the property name between "${" and "}" and placing it in the position of the task property value.
Ant provides some built-in properties that can be obtained with a list of system properties consistent with those obtained by the System.getpropertis () method in the Java document, which refer to the Sun Web site's instructions.
At the same time, Ant also provides some of its own built-in properties, as follows:
Basedir:project the absolute path of the base directory, which is explained in detail when explaining project elements, and is no longer verbose;
Ant.file:buildfile's absolute path, as in the above examples, the Ant.file value is e: "Build.xml;
The ant.version:Ant version, in this article, has a value of 1.7.0;
Ant.project.name: The name of the currently specified project, that is, the value of project's Name property as previously mentioned;
The version of the JDK that Ant.java.version:Ant detected is 1.5 in the results of the previous example run.
Let the reader see a simple example of the use of a property element. Modify the E: "Build.xml file, which reads as follows:
<?xml version= "1.0"?> <project name= "Propertystudy" default= "
example" >
<property name= "name "Value=" amigo "/>
<property name=" age "value=" a "/> <target" name= "
>
Example Message= ' name: ${name}, Age: ${age} '/>
</target>
</project>
The results of this example are as shown in the following illustration:
D:\>ant
Buildfile:build.xml
Example
[Echo] Name:amigo, age:25
Build successful
Total time:0 seconds
As this reader can see, the following two statements are adopted:
<property name= "name" value= "Amigo"/>
<property name= "age" value= "/>"
We set two properties named Name and age, and after these two properties are set, readers can get the values of these two properties, respectively, through ${name} and ${age}.
three. Ant's Common tasks
Each task in the Ant tool encapsulates the specific functionality to be performed and is the basic execution unit of the Ant tool. In this section, the reader is primarily guided to look at Ant's Common tasks and their usage examples.
1. Copy Task
This task is primarily used for copying files and directories. Examples are as follows:
Eg1. Copy a single file:
<copy file= "file.txt" tofile= "Copy.txt"/>
Eg2. Copy the file directory:
<copy todir= ". /newdir/dest_dir ">
<fileset dir=" Src_dir "/>
</copy>
Eg3. To copy a file to a different directory:
<copy file= "file.txt" todir= ". /other/dir "/>
2. Delete Task
Delete the file or directory, for example:
Eg1. To delete a file:
<delete file= "Photo/amigo.jpg"/>
Eg2. To delete a directory:
<delete dir= "Photo"/>
Eg3. Delete all backup directories or empty directories:
<delete includeemptydirs= "true" >
<fileset dir= "." includes= "**/*.bak"/>
</delete>
3. mkdir Mission
Create a directory. eg
<mkdir dir= "Build"/>
4. Move Task
Move the file or directory, for example:
Eg1. To move a single file:
<move file= "FromFile" tofile= "ToFile"/>
Eg2. To move a single file to another directory:
<move file= "FromFile" todir= "Movedir"/>
Eg3. To move a directory to another directory:
<move todir= "Newdir" >
<fileset dir= "Olddir"/>
</move>
5.echo Task
The role of this task is to output information based on the level of the log or monitor. It includes message, file, append, and level four attributes, for example:
<echo message= "Hello,amigo" file= "Logs/system.log" append= "true" >
Four. Building and deploying Java Engineering with Ant
Ant can perform Java operations in lieu of commands such as Javac, Java, and jars to make it easy to build and deploy Java engineering. Let's look at a few points of knowledge.
1. Use Ant's Javac task to compile Java programs
Ant's Javac task is used to implement the ability to compile Java programs. Let's look at a simple example:
First, we set up a Java project named Antstudy, establish the SRC directory as the source code directory, in the SRC directory to establish Helloworld.java this class of files. The contents of such a document are as follows:
public class HelloWorld {public
static void Main (string[] args) {
System.out.println ("Hello,amigo");
}
At the same time in the root directory of Antstudy project to establish Build.xml file, in the file compiled in the src directory of java files, and the compiled class file into the Build/classes directory, before compiling, you need to clear the classes directory, The contents of the document are as follows:
<?xml version= "1.0"?> <project name= "javactest" default= "compile"
. >
<target name= "clean" >
<delete dir= "Build"/>
</target>
<target name= " Compile "depends=" clean ">
<mkdir dir=" build/classes "/> <javac srcdir=
" src "destdir=" build/ Classes "/>
</target>
</project>
Running the Build.xml file, you can see the new build/classes directory in the project and build the compiled Helloworld.class file in the directory.
2. Run Java programs with ant Java Tasks
You can use Java tasks in ant to implement functions that run Java programs. The following changes are made in the 1 example below, and the revised Build.xml file reads as follows:
Reader Note: The following default property value should be run. <project name= "Javatest" default= "Run" basedir= "." >
<?xml version= "1.0"?> <project name= "javatest"
Jar "default=". >
<target name= "clean" >
<delete dir= "Build"/>
</target>
<target name= " Compile "depends=" clean ">
<mkdir dir=" build/classes "/> <javac srcdir=
" src "destdir=" build/ Classes "/>
</target>
<target name=" Run "depends=" compile ">
<java classname=" HelloWorld ">
<classpath>
<pathelement path=" build/classes "/>
</classpath>
</java>
</target>
</project>
Run the Build.xml file to see the output of the HelloWorld Main method in the console.
3. Use Ant's jar task to generate JAR files
The reader can build the jar package on the basis of the above example and add the following target under run this target:
<target name= "Jar" depends= "Run" >
<jar destfile= "Helloworld.jar" basedir= "build/classes" >
< manifest>
<attribute name= "Main-class" value= "HelloWorld"/>
</manifest>
</jar>
</target>
The ant project's default property is set to jar, and the Build.xml file is run at the same time, and you can see that a jar pack Helloworld.jar is generated in the engineering directory.
4. Use Ant's War task to package the Java EE Web project
Create a Java EE Web project whose directory structure is shown in the following illustration:
Where SRC is the source code directory, Webroot for each JSP storage directory, LIB for the project package directory. A Build.xml file is established under the Antwebproject Engineering directory, which is the ant component file for the project. The reader can be placed in the SRC directory in the previous example of the development of the Helloworld.java file, and Webroot under the index.jsp file, the content is very simple, is the output hello information, the code is as follows:
<%@ page language= "java" contenttype= "text/html; charset= "UTF-8" pageencoding= "UTF-8"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Next, write the Build.xml file, which reads as follows:
<?xml version= "1.0"?> <project name= "Antwebproject" "War" default= "." > <property name= "Classes" value= "build/classes"/> <property name= "Build" value= "Build"/> Rty name= "Lib" value= "Webroot/web-inf/lib"/> <!--Delete build path--> <target name= "clean" > <dele Te dir= "Build"/> </target> <!--establish the build/classes path and compile the class file into the build/classes path--> <target na Me= "Compile" depends= "clean" > <mkdir dir= "${classes}"/> <javac srcdir= "src" destdir= "${classes}" "/> </target> <!--playing war package--> <target name=" war "depends=" compile "> <war destfil E= "${build}/antwebproject.war" webxml= "Webroot/web-inf/web.xml" > <!--copy WebRoot the two folders in addition to Web-inf and Meta-inf- -> <fileset dir= "WebRoot" includes= "**/*.jsp"/> <!--the jar package under the copy Lib directory--> ; Lib dir= "${lib}"/> <!--copy build/classes CLass file--> <classe sdir= "${classes}"/> </war> </target> </project>
The role of each target has been explained in the content, no longer repeat. After you run the build file and update the catalog, you can see that the Antwebproject.war file is generated in the built directory, and you can see its directory structure as follows:
--meta-inf
--manifest. Mf
--index.jsp
--web-inf
--lib
--log4j-1.2.9.jar
--classes
--helloworld.class
--web.xml
Readers can copy the war package to the Tomcat directory for a look at the results of the operation.
Five. Summary
In this paper, the author describes ant installation and configuration, key elements and common tasks in detail from shallow to deep. The application of ant in our Java project is illustrated by an example, which tells us about compiling, running Java programs, and playing jar packs, war packs and so on to lead readers into Ant's Wonderful world. As you can see in this article, Ant is easy to use and flexible to build and deploy Java programs automatically, and is a great helper for our Java developers.
Project Download: Antstudy.rar, Antwebproject.rar