Ant 简明教程

Ant - Quick Guide

Ant - Introduction

ANT 代表 Another Neat 工具。它是一种来自计算机软件开发公司 Apache 的基于 Java 的构建工具。在深入了解 Apache Ant 的细节之前,让我们首先理解为什么我们需要一个构建工具。

ANT stands for Another Neat Tool. It is a Java-based build tool from computer software development company Apache. Before going into the details of Apache Ant, let us first understand why we need a build tool.

Need for a Build Tool

通常,开发人员将大量时间花在执行构建和部署等平凡任务上,其中包括−

On an average, a developer spends a substantial amount of time doing mundane tasks like build and deployment that include −

  1. Compiling the code

  2. Packaging the binaries

  3. Deploying the binaries to the test server

  4. Testing the changes

  5. Copying the code from one location to another

为了自动化和简化上述任务,Apache Ant 非常有用。它是一种可以从命令行执行的操作系统构建和部署工具。

To automate and simplify the above tasks, Apache Ant is useful. It is an Operating System build and deployment tool that can be executed from the command line.

History of Apache Ant

Ant 最初是由软件开发人员 James Duncan Davidson 创建的,他也是 web 服务器应用程序 Tomcat 的最初创建者。

Ant was created by software developer James Duncan Davidson who is also the original creator of webserver application Tomcat.

Ant 最初用于构建 Tomcat,并作为 Tomcat 发行版的一部分进行捆绑。

Ant was originally used to build Tomcat, and was bundled as a part of Tomcat distribution.

它的诞生源于与 Apache Make 工具相关的复杂性和问题。

It was born out of the problems and complexities associated with the Apache Make tool.

它于 2000 年作为 Apache 中的一个独立项目进行了推广。截至 2021 年 10 月,Apache Ant 的最新版本为 1.10.12

It was promoted as an independent project in Apache in the year 2000. The latest version of Apache Ant as on October 2021 is 1.10.12.

Features of Apache Ant

Apache Ant 的功能如下所示 −

The features of Apache Ant are listed below −

  1. It is the most complete Java build and deployment tool available.

  2. It is platform neutral and can handle platform specific properties, such as file separators.

  3. It can be used to perform platform specific tasks such as modifying the modified time of a file using 'touch' command.

  4. Ant scripts are written using plain XML. If you are already familiar with XML, you can learn Ant pretty quickly.

  5. Ant is good at automating complicated repetitive tasks.

  6. Ant comes with a big list of predefined tasks.

  7. Ant provides an interface to develop custom tasks.

  8. Ant can be easily invoked from the command line and it can integrate with free and commercial IDEs.

Ant - Environment Setup

Apache Ant 以 Apache 软件许可证分发,该许可证是开源计划认证的、成熟的开源许可证。

Apache Ant is distributed under the Apache Software License which is a fully-fledged open source license certified by the open source initiative.

最新版本的 Apache Ant, 包括了它的全源代码、类文件和文档,可以在 https://ant.apache.org 找到。

The latest Apache Ant version, including its full-source code, class files, and documentation can be found at https://ant.apache.org.

Installing Apache Ant

我们假设您已经下载并安装了 Java 开发工具包 (JDK)。如果没有,请按照 file:///C:/java/java_environment_setup.htm 的说明进行操作。

It is assumed that you have already downloaded and installed Java Development Kit (JDK) on your computer. If not, please follow the instructions available at file:///C:/java/java_environment_setup.htm

  1. Ensure that the JAVA_HOME environment variable is set to the folder, where your JDK is installed.

  2. Download the binaries from https://ant.apache.org

  3. Unzip the zip file to a convenient location c:\folder by using Winzip, winRAR, 7-zip or similar tools.

  4. Create a new environment variable called ANT_HOME that points to the Ant installation folder. In this case, it is c:\apache-ant-1.10.12-bin folder.

  5. Append the path to the Apache Ant batch file to the PATH environment variable. In our case, this would be the c:\apache-ant-1.10.12-bin\bin folder.

Verifying the Installation

在计算机中验证 Apache Ant 的安装是否成功,请在命令提示符中键入 ant。

To verify the successful installation of Apache Ant on your computer, type ant on your command prompt.

您应当看到以下输出结果:

You should see an output as given below −

C:\>ant -version
Apache Ant(TM) version 1.10.12 compiled on October 13 2021

如果您没有看到以上输出结果,请验证您是否已经正确地按照安装步骤操作。

If you do not see the above output, then please verify that you have followed the installation steps properly.

Installing Eclipse

本教程还涵盖了 Ant 和 Eclipse 集成开发环境 (IDE) 的集成。因此,如果您没有安装 Eclipse,请下载并安装 Eclipse。

This tutorial also covers integration of Ant with Eclipse integrated development environment (IDE). Hence, if you have not installed Eclipse, please download and install Eclipse.

Steps to install Eclipse

  1. Download the latest Eclipse binaries from www.eclipse.org

  2. Unzip the Eclipse binaries to a convenient location, say c:\folder.

  3. Run Eclipse from c:\eclipse\eclipse.exe.

Ant - Build Files

通常,Ant 构建文件名为 build.xml ,它应当放在项目的基本目录中。然而,对文件名或它的位置没有限制。您可以自由地使用其它文件名或将构建文件保存在其它位置。

Typically, Ant’s build file, called build.xml should reside in the base directory of the project. However, there is no restriction on the file name or its location. You are free to use other file names or save the build file in some other location.

为了进行这个练习,在计算机中任意位置创建一个名为 build.xml 的文件,它的内容如下:

For this exercise, create a file called build.xml anywhere in your computer with the following contents −

<?xml version="1.0"?>
   <project name="Hello World Project" default="info">
   <target name="info">
      <echo>Hello World - Welcome to Apache Ant!</echo>
   </target>
</project>

请注意,xml 声明之前不应有空行或空格。如果您允许空行或空格,那么在执行 ant 构建时,会导致以下错误信息:

Note that there should be no blank line(s) or whitespace(s) before the xml declaration. If you allow them, the following error message occurs while executing the ant build −

The processing instruction target matching "[xX][mM][lL]" is not allowed.
All build files require the project element and at least one target element.

XML 元素 project 有三个属性,如下:

The XML element project has three attributes which are as follows −

Sr.No

Attributes & Description

1

name The Name of the project. (Optional)

2

default The default target for the build script. A project may contain any number of targets. This attribute specifies which target should be considered as the default. (Mandatory)

3

basedir The base directory (or) the root folder for the project. (Optional)

目标是您要作为一个单元运行的任务集合。在我们的示例中,我们有一个简单的目标,为用户提供信息消息。

A target is a collection of tasks that you want to run as one unit. In our example, we have a simple target to provide an informational message to the user.

目标可以依赖于其他目标。例如, deploy 目标可能依赖于程序包目标, package 目标可能依赖于编译目标,依此类推。依赖项使用 depends 属性表示。

Targets can have dependencies on other targets. For example, a deploy target may have a dependency on the package target, the package target may have a dependency on the compile target and so forth. Dependencies are denoted using the depends attribute.

例如 -

For example −

<target name="deploy" depends="package">

   ....
</target>
<target name="package" depends="clean,compile">
   ....
</target>
<target name="clean" >
   ....
</target>
<target name="compile" >
   ....
</target>

目标元素具有以下属性:

The target element has the following attributes −

Sr.No

Attributes & Description

1

name The name of the target (Required)

2

depends Comma separated list of all targets that this target depends on. (Optional)

3

description A short description of the target. (optional)

4

if Allows the execution of a target based on the trueness of a conditional attribute. (optional)

5

unless Adds the target to the dependency list of the specified Extension Point. An Extension Point is similar to a target, but it does not have any tasks. (Optional)

上述示例中的 echo 任务是一个打印消息的简单任务。在我们的示例中,它打印消息 Hello World

The echo task in the above example is a trivial task that prints a message. In our example,it prints the message Hello World.

要运行蚂蚁构建文件,请打开命令提示符并导航到 build.xml 所在的文件夹,然后键入 ant info 。你也可以键入 ant 。两者都会起作用,因为 info 是构建文件中的默认目标。

To run the ant build file, open up command prompt and navigate to the folder, where the build.xml resides, and then type ant info. You could also type ant instead. Both will work,because info is the default target in the build file.

你应该看到以下输出:

You should see the following output −

C:\>ant
Buildfile: C:\build.xml

info: [echo] Hello World - Welcome to Apache Ant!

BUILD SUCCESSFUL
Total time: 0 seconds

C:\>

Ant - Property Task

Ant 构建文件以 XML 编写,这不允许您像在您喜欢的编程语言中那样声明变量。不过,您可能已经想象到了,如果 Ant 允许声明变量(如项目名称、项目源目录等),那将很有用。

Ant build files are written in XML, which does not allow declaring variables as you do in your favorite programming language. However, as you may have imagined, it would be useful if Ant allowed declaring variables such as project name, project source directory, etc.

Ant 使用 property 元素,它允许你指定属性。这允许属性在不同的构建或不同的环境中更改。

Ant uses the property element which allows you to specify the properties. This allows the properties to be changed from one build to another or from one environment to another.

Ant Properties

默认情况下,Ant 提供了以下预定义的属性,这些属性可以在构建文件中使用:

By default, Ant provides the following pre-defined properties that can be used in the build file −

Sr.No

Properties & Description

1

ant.file The full location of the build file.

2

ant.version The version of the Apache Ant installation.

3

basedir The basedir of the build, as specified in the basedir attribute of the project element.

4

ant.java.version The version of the JDK that is used by Ant.

5

ant.project.name The name of the project, as specified in the name attribute of the project element.

6

ant.project.default-target The default target of the current project.

7

ant.project.invoked-targets Comma separated list of the targets that were invoked in the current project.

8

ant.core.lib The full location of the Ant jar file.

9

ant.home The home directory of Ant installation.

10

ant.library.dir The home directory for Ant library files - typically ANT_HOME/lib folder.

Ant 也使系统属性(示例:file.separator)可用于构建文件。

Ant also makes the system properties (Example: file.separator) available to the build file.

除了以上内容,用户可以使用 property 元素定义附加的属性。

In addition to the above, the user can define additional properties using the property element.

以下示例展示了如何定义一个名为 sitename 的属性:

The following example shows how to define a property called sitename

<?xml version="1.0"?>
<project name="Hello World Project" default="info">

   <property name="sitename" value="www.tutorialspoint.com"/>
   <target name="info">
      <echo>Apache Ant version is ${ant.version} - You are at ${sitename} </echo>
   </target>
</project>

在上述构建文件上运行 Ant 会生成以下输出:

Running Ant on the above build file produces the following output −

C:\>ant
Buildfile: C:\build.xml

info: [echo] Apache Ant version is Apache Ant(TM) version 1.10.12
   compiled on October 13 2021 - You are at www.tutorialspoint.com

BUILD SUCCESSFUL
Total time: 0 seconds
C:\>

Ant - Property Files

如果只需使用少数几个属性,则直接在构建文件中设置属性就足够了。但是,对于大型项目而言,将属性存储在单独的属性文件中有意义。

Setting properties directly in the build file is fine, if you are working with a handful of properties. However, for a large project, it makes sense to store the properties in a separate property file.

Benefits

将属性存储在单独的文件中会带来以下好处:

Storing the properties in a separate file offers the following benefits −

  1. It allows you to reuse the same build file, with different property settings for different execution environment. For example, build properties file can be maintained separately for DEV, TEST, and PROD environments.

  2. It is useful, when you do not know the values for a property (in a particular environment) up-front. This allows you to perform the build in other environments, where the property value is known.

没有硬性规定,但通常属性文件被命名为 build.properties ,并与 build.xml 文件放在一起。你可以根据部署环境创建多个构建属性文件,比如 build.properties.devbuild.properties.test

There is no hard and fast rule, but typically the property file is named as build.properties and is placed along-side the build.xml file. You could create multiple build properties files based on the deployment environments - such as build.properties.dev and build.properties.test.

构建属性文件的文本内容与规范的 java 属性文件类似。它们每行包含一个属性。每个属性由名称和值对表示。

The contents of the build property file are similar to the normal java property file. They contain one property per line. Each property is represented by a name and a value pair.

名称和值对用等号 (=) 符号分隔。强烈建议使用正确的注释为这些属性做注解。使用井号 (#) 字符列出注释。

The name and value pairs are separated by an equals (=) sign. It is highly recommended that the properties are annotated with proper comments. Comments are listed using the hash (#) character.

以下示例展示了一个 build.xml 文件及其关联 build.properties 文件−

The following example shows a build.xml file and its associated build.properties file −

build.xml

以下是针对 build.xml 文件的示例。

Given below is an example for build.xml file.

<?xml version="1.0"?>
<project name="Hello World Project" default="info">
   <property file="build.properties"/>
      <target name="info">
         <echo>Apache Ant version is ${ant.version} - You are at ${sitename} </echo>
      </target>
</project>

build.properties

以下是针对 build.properties 文件的示例 −

An example for build.properties file is mentioned below −

# The Site Name
sitename=www.tutorialspoint.com
buildversion=3.3.2

在上述示例中, sitename 是映射到网站名称的自定义属性。您可以用这种方式声明任意数量的自定义属性。

In the above example, sitename is a custom property which is mapped to the website name. You can declare any number of custom properties in this fashion.

上述示例中列出的另一个自定义属性是 buildversion ,它在这种情况下指代构建版本。

Another custom property listed in the above example is the buildversion, which, in this instance, refers to the version of the build.

除上述内容外,Ant 内含若干预定义构建属性,已在上一部分中列出,但在此再次列出以供参考。

In addition to the above, Ant comes with a number of predefined build properties, which are listed in the previous section, but is given below once again for your reference.

Sr.No

Properties & Description

1

ant.file The full location of the build file.

2

ant.version The version of the Apache Ant installation.

3

basedir The basedir of the build, as specified in the basedir attribute of the project element.

4

ant.java.version The version of the JDK that is used by Ant.

5

ant.project.name The name of the project, as specified in the name attribute of the project element.

6

ant.project.default-target The default target of the current project.

7

ant.project.invoked-targets Comma separated list of the targets that were invoked in the current project.

8

ant.core.lib The full location of the Ant jar file.

9

ant.home The home directory of Ant installation.

10

ant.library.dir The home directory for Ant library files - typically ANT_HOME/lib folder.

本章展示的示例使用了 ant.version 内置属性。

The example presented in this chapter uses the ant.version built-in property.

Ant - Data Types

Ant 提供了许多预定义的数据类型。不要将术语“数据类型”与编程语言中可用的数据类型混淆。相反,将它们视为已经内置到产品中的服务集。

Ant provides a number of predefined data types. Do not confuse the term "data types" with those that are available in the programming language. Instead, consider them as a set of services that are built into the product already.

Data Types in Ant

Apache Ant 提供了以下数据类型。

The following data types are provided by Apache Ant.

Fileset

文件集数据类型表示一组文件。它用作过滤器,用于包括或排除与特定模式匹配的文件。

The fileset data type represents a collection of files. It is used as a filter to include or exclude files that match a particular pattern.

例如,请参阅以下代码。此处,src 属性指向项目的源文件夹。

For example, refer the following code. Here, the src attribute points to the source folder of the project.

<fileset dir="${src}" casesensitive="yes">
   <include name="**/*.java"/>
   <exclude name="**/*Stub*"/>
</fileset>

文件集选择源文件夹中的所有 .java 文件,但那些包含单词“Stub”的文件除外。对文件集应用区分大小写的过滤器,这意味着不会从文件集排除名为 Samplestub.java 的文件。

The fileset selects all .java files in the source folder except those contain the word 'Stub'.The case-sensitive filter is applied to the fileset, which means a file with the name Samplestub.java will not be excluded from the fileset.

Pattern set

模式集是一种模式,允许根据某些模式轻松过滤文件或文件夹。可以使用以下元字符创建模式:

A pattern set is a pattern that allows to filter files or folders easily based on certain patterns. The patterns can be created using the following meta characters −

  1. ? - Matches one character only.

  2. - Matches zero or many characters.

  3. ** - Matches zero or many directories recursively.

以下示例描述了模式集的用法。

The following example depicts the usage of a pattern set.

<patternset id="java.files.without.stubs">
   <include name="src/**/*.java"/>
   <exclude name="src/**/*Stub*"/>
</patternset>

然后可以将模式集与文件集一起重新使用,如下所示:

The patternset can then be reused with a fileset as follows −

<fileset dir="${src}" casesensitive="yes">
   <patternset refid="java.files.without.stubs"/>
</fileset>

File list

文件列表数据类型与文件集类似,但存在以下差异:

The filelist data type is similar to the file set except the following differences −

  1. It contains explicitly named lists of files and it does not support wild cards.

  2. This data type can be applied for existing or non-existing files.

让我们看一下文件列表数据类型的以下示例。在此处,属性 webapp.src.folder 指向项目的 Web 应用程序源文件夹。

Let us see the following example of the filelist data type. Here, the attribute webapp.src.folder points to the web application source folder of the project.

<filelist id="config.files" dir="${webapp.src.folder}">
   <file name="applicationConfig.xml"/>
   <file name="faces-config.xml"/>
   <file name="web.xml"/>
   <file name="portlet.xml"/>
</filelist>

Filter set

通过将 filterset 数据类型与 copy 任务一起使用,可以使用替换值替换与模式匹配的所有文件中特定的文本。

By using a filterset data type along with the copy task, you can replace certain text in all the files that matches the pattern with a replacement value.

一个常见的例子是在发布说明文件中追加版本号,如下面的代码所示。

A common example is to append the version number to the release notes file, as shown in the following code.

<copy todir="${output.dir}">
   <fileset dir="${releasenotes.dir}" includes="**/*.txt"/>
   <filterset>
      <filter token="VERSION" value="${current.version}"/>
   </filterset>
</copy>

在上面提到的代码中:

In the above mentioned code −

  1. The attribute output.dir points to the output folder of the project.

  2. The attribute releasenotes.dir points to the release notes folder of the project.

  3. The attribute current.version points to the current version folder of the project.

  4. The copy task, as the name suggests, is used to copy files from one location to another.

Path

path 数据类型通常用于表示类路径。路径中的条目使用分号或冒号分隔。但是,这些字符会在运行时被执行系统的路径分隔符字符替换。

The path data type is commonly used to represent a class-path. Entries in the path are separated using semicolons or colons. However, these characters are replaced at the runtime by the executing system’s path separator character.

类路径被设置为项目中 jar 文件和类的列表,如下面的示例所示。

The classpath is set to the list of jar files and classes in the project, as shown in the example below.

<path id="build.classpath.jar">
   <pathelement path="${env.J2EE_HOME}/${j2ee.jar}"/>
   <fileset dir="lib">
      <include name="**/*.jar"/>
   </fileset>
</path>

在上面给出的代码中:

In the code given above −

  1. The attribute env.J2EE_HOME points to the environment variable J2EE_HOME.

  2. The attribute j2ee.jar points to the name of the J2EE jar file in the J2EE base folder.

Ant - Building Projects

既然我们已学习了 Ant 中的数据类型,是时候将这份知识付诸实践了。我们将在本章中构建一个项目。本章的目标是构建一个 Ant 文件,编译 Java 类并将其置于 WEB-INF\classes 文件夹中。

Now that we have learnt about the data types in Ant, it is time to put that knowledge into practice. We will build a project in this chapter. The aim of this chapter is to build an Ant file that compiles the java classes and places them in the WEB-INF\classes folder.

考虑以下项目结构:

Consider the following project structure −

  1. The database scripts are stored in the db folder.

  2. The java source code is stored in the src folder.

  3. The images, js, META-INF, styles (css) are stored in the war folder.

  4. The Java Server Pages (JSPs) are stored in the jsp folder.

  5. The third party jar files are stored in the lib folder.

  6. The java class files are stored in the WEB-INF\classes folder.

该项目构成了本教程其余部分的 Hello World 传真应用程序。

This project forms the Hello World Fax Application for the rest of this tutorial.

C:\work\FaxWebApplication>tree
Folder PATH listing
Volume serial number is 00740061 EC1C:ADB1
C:.
+---db
+---src
. +---faxapp
. +---dao
. +---entity
. +---util
. +---web
+---war
   +---images
   +---js
   +---META-INF
   +---styles
   +---WEB-INF
      +---classes
      +---jsp
      +---lib

以下是该项目所需的 build.xml 。让我们逐件考虑。

Here is the build.xml required for this project. Let us consider it piece by piece.

<?xml version="1.0"?>
<project name="fax" basedir="." default="build">
   <property name="src.dir" value="src"/>
   <property name="web.dir" value="war"/>
   <property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
   <property name="name" value="fax"/>

   <path id="master-classpath">
      <fileset dir="${web.dir}/WEB-INF/lib">
         <include name="*.jar"/>
      </fileset>
      <pathelement path="${build.dir}"/>
   </path>

   <target name="build" description="Compile source tree java files">
      <mkdir dir="${build.dir}"/>
      <javac destdir="${build.dir}" source="1.5" target="1.5">
         <src path="${src.dir}"/>
         <classpath refid="master-classpath"/>
      </javac>
   </target>

   <target name="clean" description="Clean output directories">
      <delete>
         <fileset dir="${build.dir}">
            <include name="**/*.class"/>
         </fileset>
      </delete>
   </target>
</project>

首先,让我们为源文件、Web 和构建文件夹声明一些属性。

First, let us declare some properties for the source, web, and build folders.

<property name="src.dir" value="src"/>
<property name="web.dir" value="war"/>
<property name="build.dir" value="${web.dir}/WEB-INF/classes"/>

在上述示例中,

In the above mentioned example −

  1. src.dir refers to the source folder of the project, where the java source files can be found.

  2. web.dir refers to the web source folder of the project, where you can find the JSPs,web.xml, css, javascript and other web related files

  3. build.dir refers to the output folder of the project compilation.

属性可以引用其他属性。如上述示例所示, build.dir 属性引用 web.dir 属性。

Properties can refer to other properties. As shown in the above example, the build.dir property makes a reference to the web.dir property.

在此示例中, src.dir 指的是项目的源文件夹。

In this example, the src.dir refers to the source folder of the project.

我们项目的默认目标是 compile 目标。但首先,让我们看一下 clean 目标。

The default target of our project is the compile target. But first, let us look at the clean target.

正如名称所示,clean 目标将删除构建文件夹中的文件。

The clean target, as the name suggests, deletes the files in the build folder.

<target name="clean" description="Clean output directories">
   <delete>
      <fileset dir="${build.dir}">
         <include name="**/*.class"/>
      </fileset>
   </delete>
</target>

master-classpath 保存类路径信息。在这种情况下,它包括构建文件夹中的类和 lib 文件夹中的 jar 文件。

The master-classpath holds the classpath information. In this case, it includes the classes in the build folder and the jar files in the lib folder.

<path id="master-classpath">
   <fileset dir="${web.dir}/WEB-INF/lib">
      <include name="*.jar"/>
   </fileset>
   <pathelement path="${build.dir}"/>
</path>

最后,构建目标用于构建文件。

Finally, the build targets to build the files.

首先,如果构建目录不存在,我们将创建它,然后执行 javac 命令(指定 jdk1.5 作为目标编译)。我们向 javac 任务提供源文件夹和类路径,并要求它将类文件放入构建文件夹中。

First of all, we create the build directory, if it does not exist, then, we execute the javac command (specifying jdk1.5 as our target compilation). We supply the source folder and the classpath to the javac task and ask it to drop the class files in the build folder.

<target name="build" description="Compile main source tree java files">
   <mkdir dir="${build.dir}"/>
   <javac destdir="${build.dir}" source="1.5" target="1.5"
      debug="true" deprecation="false" optimize="false" failonerror="true">

      <src path="${src.dir}"/>
      <classpath refid="master-classpath"/>
   </javac>
</target>

在此文件中执行 Ant 会编译 Java 源文件,并将类放入构建文件夹中。

Executing Ant on this file compiles the java source files and places the classes in the build folder.

运行 Ant 文件后,会产生以下结果 −

The following outcome is the result of running the Ant file −

C:\>ant
Buildfile: C:\build.xml

BUILD SUCCESSFUL
Total time: 6.3 seconds

文件会编译并在 build.dir 文件夹中以 build 文件夹中放置。

The files are compiled and placed in the build.dir folder.

Ant - Build Documentation

文档在任何项目中都是必不可少的。文档在项目的维护中发挥了重要作用。Java 通过使用内置 javadoc 工具简化了文档的编写。Ant 通过按需生成文档,进一步简化了这一过程。

Documentation is a must in any project. Documentation plays a great role in the maintenance of a project. Java makes documentation easier by the use of the inbuilt javadoc tool. Ant makes it even easier by generating the documentation on demand.

众所周知,javadoc 工具非常灵活,并允许使用许多配置选项。Ant 通过 javadoc 任务公开这些配置选项。如果您不熟悉 javadoc,建议您从这篇 Java 文档教程开始学习。

As you know, the javadoc tool is highly flexible and allows a number of configuration options. Ant exposes these configuration options via the javadoc task. If you are unfamiliar with javadocs, we suggest that you start with this Java Documentation Tutorial.

以下部分列出了 Ant 中使用的一些最常见的 javadoc 选项。

The following section lists the most commonly used javadoc options that are used in Ant.

Attributes

源可以通过 sourcepathsourcepathrefsourcefiles 指定。

Source can be specified using sourcepath, sourcepathref or sourcefiles.

  1. sourcepath is used to point to the folder of the source files (e.g. src folder).

  2. sourcepathref is used to refer a path that is referenced by the path attribute (e.g, delegates.src.dir).

  3. sourcefiles is used when you want to specify the individual files as a comma separated list.

目标路径是使用 destdir 文件夹指定的(例如 build.dir)。

Destination path is specified using the destdir folder (e.g build.dir).

您可以通过指定要包含的程序包名称来过滤 javadoc 任务。这是通过使用 packagenames 属性(逗号分隔的程序包文件列表)来实现的。

You could filter the javadoc task by specifying the package names which are to be included. This is achieved by using the packagenames attribute, a comma separated list of package files.

您可以过滤 javadoc 进程,以仅显示 public、private、package 或 protected 类和成员。这是通过使用 privatepublicpackageprotected 属性实现的。

You could filter the javadoc process to show only the public, private, package, or protected classes and members. This is achieved by using the private, public, package and protected attributes.

您还可以通过使用相应属性来告诉 javadoc 任务包含作者和版本信息。

You could also tell the javadoc task to include the author and version information by using the respective attributes.

您还可以使用 group 属性对包进行分组,以便于导航。

You could also group the packages together using the group attribute, so that it becomes easy to navigate.

Putting it all together

让我们继续 Hello world 传真应用程序的主题,并向传真应用程序项目添加文档目标。

Let us continue our theme of the Hello world Fax application and add a documentation target to our Fax application project.

下面给出了项目中使用的一个 javadoc 任务示例。在此示例中,我们指定 javadoc 使用 src.dir 作为源目录,使用 doc 作为目标。

Given below is an example javadoc task used in our project. In this example, we have specified the javadoc to use the src.dir as the source directory, and doc as the target.

我们还自定义了显示在 java 文档页面上的窗口标题、页眉和页脚信息。

We have also customised the window title, the header, and the footer information that appear on the java documentation pages.

此外,我们还创建了三个组:

Also, we have created three groups −

  1. one for the utility classes in our source folder,

  2. one for the user interfaces classes, and

  3. one for the database related classes.

你可能会注意到,data 包组有两个包——faxapp.entity 和 faxapp.dao。

You may notice that the data package group has two packages -– faxapp.entity and faxapp.dao.

<target name="generate-javadoc">
   <javadoc packagenames="faxapp.*" sourcepath="${src.dir}"
      destdir="doc" version="true" windowtitle="Fax Application">
      <doctitle><![CDATA[= Fax Application =]]></doctitle>
      <bottom>
         <![CDATA[Copyright © 2011. All Rights Reserved.]]>
      </bottom>
      <group title="util packages" packages="faxapp.util.*"/>
      <group title="web packages" packages="faxapp.web.*"/>
      <group title="data packages" packages="faxapp.entity.*:faxapp.dao.*"/>
   </javadoc>
   <echo message="java doc has been generated!" />
</target>

让我们执行 javadoc Ant 任务。它会在 doc 文件夹中生成并放置 java 文档文件。

Let us execute the javadoc Ant task. It generates and places the java documentation files in the doc folder.

javadoc target 执行时,它会生成以下结果 −

When the javadoc target is executed, it produces the following outcome −

C:\>ant generate-javadoc
Buildfile: C:\build.xml

java doc has been generated!

BUILD SUCCESSFUL
Total time: 10.63 second

java 文档文件现在存在于 doc 文件夹中。

The java documentation files are now present in the doc folder.

通常,javadoc 文件在发行或包目标中生成。

Typically, the javadoc files are generated as a part of the release or package targets.

Ant - Creating JAR files

在编译完 java 源文件后的下一个逻辑步骤,就是构建 java 存档,即 Java 存档 (JAR) 文件。用 Ant 创建 JAR 文件非常容易,只需要 jar 任务。

The next logical step after compiling your java source files, is to build the java archive, i.e., the Java Archive (JAR) file. Creating JAR files with Ant is quite easy with the jar task.

Attributes

jar 任务常用的属性如下 −

The commonly used attributes of the jar task are as follows −

Sr.No

Attributes & Description

1

basedir The base directory for the output JAR file. By default, this is set to the base directory of the project.

2

compress Advises Ant to compress the file as it creates the JAR file.

3

keepcompression While the compress attribute is applicable to the individual files, the keepcompression attribute does the same thing, but it applies to the entire archive.

4

destfile The name of the output JAR file.

5

duplicate Advises Ant on what to do when duplicate files are found. You could add, preserve, or fail the duplicate files.

6

excludes Advises Ant to not include these comma separated list of files in the package.

7

excludesfile Same as above, except the exclude files are specified using a pattern.

8

inlcudes Inverse of excludes.

9

includesfile Inverse of excludesfile.

10

update Advises Ant to overwrite files in the already built JAR file.

续我们的 Hello World 传真应用程序项目,让我们添加一个新目标来生成 jar 文件。

Continuing our Hello World Fax Application project, let us add a new target to produce the jar files.

但是在这样做之前,我们考虑一下给定以下 jar 任务。

But before that, let us consider the jar task given below.

<jar destfile="${web.dir}/lib/util.jar"
   basedir="${build.dir}/classes"
   includes="faxapp/util/**"
   excludes="**/Test.class"
/>

在这里, web.dir 属性指向 Web 源文件的路径。在我们的案例中,这会放置 util.jar 的位置。

Here, the web.dir property points to the path of the web source files. In our case, this is where the util.jar will be placed.

此示例中的 build.dir 属性指向 build 文件夹,此文件夹中可以找到 util.jar 的类文件。

The build.dir property in this example, points to the build folder, where the class files for the util.jar can be found.

在此示例中,我们使用 faxapp.util. * 包中的类创建了一个名为 util.jar 的 jar 文件。但是,我们会排除以 Test 名称结尾的类。输出 jar 文件将被放置在 Web 应用程序 lib 文件夹中。

In this example, we create a jar file called util.jar using the classes from the faxapp.util.* package. However, we are excluding the classes that end with the name Test. The output jar file will be placed in the web application lib folder.

如果我们要使 util.jar 成为可执行 jar 文件,需要使用带有 Main-Class 元属性的 manifest

If we want to make the util.jar an executable jar file, we need to add the manifest with the Main-Class meta attribute.

因此,上面的示例将更新如下:

Therefore, the above example will be updated as follows −

<jar destfile="${web.dir}/lib/util.jar"
   basedir="${build.dir}/classes"
   includes="faxapp/util/**"
   excludes="**/Test.class" class="ts"
   <manifest class="ts"
      <attribute name="Main-Class" value="com.tutorialspoint.util.FaxUtil"/>
   </manifest class="ts"
</jar class="ts"

要执行 jar 任务,请将其包装到目标内,最常见的是 build 或 package 目标,然后执行它们。

To execute the jar task, wrap it inside a target, most commonly, the build or package target, and execute them.

<target name="build-jar" class="ts"
<jar destfile="${web.dir}/lib/util.jar"
   basedir="${build.dir}/classes"
   includes="faxapp/util/**"
   excludes="**/Test.class" class="ts"
   <manifest class="ts"
      <attribute name="Main-Class" value="com.tutorialspoint.util.FaxUtil"/>
   </manifest class="ts"
</jar class="ts"
</target class="ts"

在此文件中运行 Ant 会为我们创建 util.jar 文件。

Running Ant on this file creates the util.jar file for us.

运行 Ant 文件后,会产生以下结果 −

The following outcome is the result of running the Ant file −

C:\ class="ts"ant build-jar
Buildfile: C:\build.xml

BUILD SUCCESSFUL
Total time: 1.3 seconds

util.jar 文件现在放置在输出文件夹中。

The util.jar file is now placed in the output folder.

Ant - Create WAR Files

使用 Ant 创建 Web 归档 (WAR) 文件极其简单,且与创建 JAR 文件任务非常类似。毕竟,WAR 文件与 JAR 文件一样,都只是另一个 ZIP 文件。

Creating Web Archive (WAR) files with Ant is extremely simple, and very similar to the creating JAR files task. After all, WAR file, like JAR file is just another ZIP file.

WAR 任务是 JAR 任务的一个扩展,但它有一些不错的补充内容,可以操作进入 WEB-INF/classes 文件夹的内容,并生成 web.xml 文件。WAR 任务对于指定 WAR 文件的特定布局非常有用。

The WAR task is an extension to the JAR task, but it has some nice additions to manipulate what goes into the WEB-INF/classes folder, and generating the web.xml file. The WAR task is useful to specify a particular layout of the WAR file.

由于 WAR 任务是 JAR 任务的扩展,因此 JAR 任务的所有属性都适用于 WAR 任务。

Since, the WAR task is an extension of the JAR task, all attributes of the JAR task apply to the WAR task.

Sr.No

Attributes & Description

1

webxml Path to the web.xml file.

2

lib A grouping to specify what goes into the WEB-INF\lib folder.

3

classes A grouping to specify what goes into the WEB-INF\classes folder.

4

metainf Specifies the instructions for generating the MANIFEST.MF file.

继续我们的 Hello World Fax Application 项目,让我们添加一个新目标以生成 jar 文件。但在添加目标之前,让我们考虑一下 war 任务。

Continuing our Hello World Fax Application project, let us add a new target to produce the jar files. But before that, let us consider the war task.

考虑以下示例 −

Consider the following example −

<war destfile="fax.war" webxml="${web.dir}/web.xml">
   <fileset dir="${web.dir}/WebContent">
      <include name="**/*.*"/>
   </fileset>
   <lib dir="thirdpartyjars">
      <exclude name="portlet.jar"/>
   </lib>
   <classes dir="${build.dir}/web"/>
</war>

如同之前的示例中提到的, web.dir 变量指源 web 文件夹,即包含 JSP、CSS、javascript文件等的文件夹。

As per the previous examples, the web.dir variable refers to the source web folder, i.e., the folder that contains the JSP, css, javascript files etc.

build.dir 变量指输出文件夹。此处可以找到 WAR 软件包的类。通常情况下,类将被捆绑到 WAR 文件的 WEB-INF/classes 文件夹中。

The build.dir variable refers to the output folder. This is where the classes for the WAR package can be found. Typically, the classes will be bundled into the WEB-INF/classes folder of the WAR file.

在此示例中,我们创建一个名为 fax.war 的 war 文件。WEB.XML 文件是从 web 源文件夹获取的。web 下的“WebContent”文件夹中的所有文件都会被复制到 WAR 文件中。

In this example, we are creating a war file called fax.war. The WEB.XML file is obtained from the web source folder. All files from the 'WebContent' folder under web are copied into the WAR file.

WEB-INF/lib 文件夹使用 thirdpartyjars 文件夹中的 jar 文件填充。然而,我们排除了 portlet.jar,因为它已经出现在应用程序服务器的 lib 文件夹中。最后,我们从 build 目录的 web 文件夹中复制所有类,并将它们放入 WEB-INF/classes 文件夹中。

The WEB-INF/lib folder is populated with the jar files from the thirdpartyjars folder. However, we are excluding the portlet.jar as this is already present in the application server’s lib folder. Finally, we are copying all classes from the build directory’s web folder and putting them into the WEB-INF/classes folder.

将 war 任务包装在 Ant 目标(通常是软件包)中并运行它。这将在指定位置创建 WAR 文件。

Wrap the war task inside an Ant target (usually package) and run it. This will create the WAR file in the specified location.

完全有可能嵌套类、lib、metainf 和 webinf 目录,以便他们居住在项目结构中任何地方的分散文件夹中。但是,最佳实践建议您的 Web 项目的 Web 内容结构应类似于 WAR 文件的结构。Fax 应用程序项目使用此基本原则概述了其结构。

It is entirely possible to nest the classes, lib, metainf and webinf directors, so that they live in scattered folders anywhere in the project structure. But, best practices suggest that your Web project should have the Web Content structure that is similar to the structure of the WAR file. The Fax Application project has its structure outlined using this basic principle.

要执行 war 任务,请将其包装在目标(最常见的是 build 或软件包目标)中,然后运行它们。

To execute the war task, wrap it inside a target, most commonly, the build or package target, and run them.

<target name="build-war">
   <war destfile="fax.war" webxml="${web.dir}/web.xml">
   <fileset dir="${web.dir}/WebContent">
      <include name="**/*.*"/>
   </fileset>
   <lib dir="thirdpartyjars">
      <exclude name="portlet.jar"/>
   </lib>
   <classes dir="${build.dir}/web"/>
   </war>
</target>

在此文件中运行 Ant 将为我们创建 fax.war 文件。

Running Ant on this file will create the fax.war file for us.

运行 Ant 文件后,会产生以下结果 −

The following outcome is the result of running the Ant file −

C:\>ant build-war
Buildfile: C:\build.xml

BUILD SUCCESSFUL
Total time: 12.3 seconds

fax.war 文件现在放置在输出文件夹中。war 文件的内容将如下所示 −

The fax.war file is now placed in the output folder. The contents of the war file will be as mentioned below −

fax.war:
   +---jsp This folder contains the jsp files
   +---css This folder contains the stylesheet files
   +---js This folder contains the javascript files

   +---images This folder contains the image files
   +---META-INF This folder contains the Manifest.Mf
   +---WEB-INF
      +---classes This folder contains the compiled classes
      +---lib Third party libraries and the utility jar files
      WEB.xml Configuration file that defines the WAR package

Ant - Packaging Applications

我们已零散地了解了 Hello World Fax Web 应用程序中使用 Ant 的不同方面。

We have learnt the different aspects of Ant using the Hello World Fax web application in bits and pieces.

现在,是时候将所有内容放在一起,以创建一个完整而全面的 build.xml 文件了。考虑 build.propertiesbuild.xml 文件如下:

Now, it is time to put everything together to create a full and complete build.xml file.Consider build.properties and build.xml files as follows −

build.properties

build.properties 文件中的内容如下。

The file is given below for build.properties.

deploy.path=c:\tomcat6\webapps

build.xml

build.xml 文件如下:

The build.xml file is as follows −

<?xml version="1.0"?>

<project name="fax" basedir="." default="usage">
   <property file="build.properties"/>
   <property name="src.dir" value="src"/>
   <property name="web.dir" value="war"/>
   <property name="javadoc.dir" value="doc"/>
   <property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
   <property name="name" value="fax"/>

   <path id="master-classpath">
      <fileset dir="${web.dir}/WEB-INF/lib">
         <include name="*.jar"/>
      </fileset>
      <pathelement path="${build.dir}"/>
   </path>

   <target name="javadoc">
      <javadoc packagenames="faxapp.*" sourcepath="${src.dir}"
         destdir="doc" version="true" windowtitle="Fax Application">
      <doctitle><![CDATA[<h1>= Fax Application =</h1>]]></doctitle>
      <bottom><![CDATA[Copyright © 2011. All Rights Reserved.]]></bottom>
      <group title="util packages" packages="faxapp.util.*"/>
      <group title="web packages" packages="faxapp.web.*"/>
      <group title="data packages" packages="faxapp.entity.*:faxapp.dao.*"/>
      </javadoc>
   </target>

   <target name="usage">
      <echo message=""/>
      <echo message="${name} build file"/>
      <echo message="-----------------------------------"/>
      <echo message=""/>
      <echo message="Available targets are:"/>
      <echo message=""/>
      <echo message="deploy --> Deploy application as directory"/>
      <echo message="deploywar --> Deploy application as a WAR file"/>
      <echo message=""/>
   </target>

   <target name="build" description="Compile main source tree java files">
      <mkdir dir="${build.dir}"/>
      <javac destdir="${build.dir}" source="1.5"
         target="1.5" debug="true"
         deprecation="false" optimize="false" failonerror="true">
         <src path="${src.dir}"/>
         <classpath refid="master-classpath"/>
      </javac>
   </target>
   <target name="deploy" depends="build" description="Deploy application">

   <copy todir="${deploy.path}/${name}" preservelastmodified="true">
      <fileset dir="${web.dir}">
         <include name="**/*.*"/>
      </fileset>
   </copy>
   </target>

   <target name="deploywar" depends="build" description="Deploy application as a WAR file">
      <war destfile="${name}.war" webxml="${web.dir}/WEB-INF/web.xml">
         <fileset dir="${web.dir}">
            <include name="**/*.*"/>
         </fileset>
      </war>
      <copy todir="${deploy.path}" preservelastmodified="true">
         <fileset dir=".">
            <include name="*.war"/>
         </fileset>
      </copy>
   </target>

   <target name="clean" description="Clean output directories">
      <delete>
         <fileset dir="${build.dir}">
            <include name="**/*.class"/>
         </fileset>
      </delete>
   </target>
</project>

在上述示例中,

In the above mentioned example −

  1. We first declare the path to the webapps folder in Tomcat in the build properties file as the deploy.path variable.

  2. We also declare the source folder for the java files in the src.dir variable.

  3. Then, we declare the source folder for the web files in the web.dir variable. javadoc.dir is the folder for storing the java documentation, and build.dir is the path for storing the build output files.

  4. After that, we declare the name of the web application, which is fax in our case.

  5. We also define the master class path, which contains the JAR files present in the WEB-INF/lib folder of the project.

  6. We also include the class files present in the build.dir in the master class path.

  7. The Javadoc target produces the javadoc required for the project and the usage target is used to print the common targets that are present in the build file.

上面的示例展示了两个部署目标 − deploydeploywar .

The above example shows two deployment targets − deploy and deploywar.

部署目标从 Web 目录将文件复制到部署目录,同时保留上次修改的时间戳。这对于部署到支持热部署的服务器时非常有用。

The deploy target copies the files from the web directory to the deploy directory preserving the last modified date time stamp. This is useful, when deploying to a server that supports hot deployment.

clean 目标清除先前构建的所有文件。

The clean target clears all the previously built files.

deploywar 目标构建 war 文件,然后将 war 文件复制到应用程序服务器的部署目录。

The deploywar target builds the war file and then, copies the war file to the deploy directory of the application server.

Ant - Deploying Applications

在之前的章节中,我们学习了如何打包应用程序并将其部署到文件夹中。

In the previous chapter, we have learnt how to package an application and deploy it to a folder.

本章中,我们将 Web 应用程序直接部署到应用程序服务器的部署文件夹中,然后添加一些 Ant 目标来启动和停止服务。

In this chapter, we are going to deploy the web application directly to the application server deploy folder and then, we are going to add a few Ant targets to start and stop the services.

我们继续使用 Hello World fax Web 应用程序。这是上一章的继续;新组件在 bold 中突出显示。

Let us continue with the Hello World fax web application. This is a continuation of the previous chapter; the new components are highlighted in bold.

build.properties

build.properties 的文件如下 −

The file for build.properties is given below −

# Ant properties for building the springapp
appserver.home=c:\\install\\apache-tomcat-7.0.19

# for Tomcat 5 use $appserver.home}/server/lib
# for Tomcat 6 use $appserver.home}/lib
appserver.lib=${appserver.home}/lib

deploy.path=${appserver.home}/webapps

tomcat.manager.url=https://www.tutorialspoint.com:8080/manager
tomcat.manager.username=tutorialspoint
tomcat.manager.password=secret

build.xml

build.xml 的文件如下 −

The file for build.xml is as follows −

<?xml version="1.0"?>

<project name="fax" basedir="." default="usage">
   <property file="build.properties"/>
   <property name="src.dir" value="src"/>
   <property name="web.dir" value="war"/>
   <property name="javadoc.dir" value="doc"/>
   <property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
   <property name="name" value="fax"/>

   <path id="master-classpath">
      <fileset dir="${web.dir}/WEB-INF/lib">
         <include name="*.jar"/>
      </fileset>
   <pathelement path="${build.dir}"/>
   </path>

   <target name="javadoc">
      <javadoc packagenames="faxapp.*" sourcepath="${src.dir}"
         destdir="doc" version="true" windowtitle="Fax Application">
         <doctitle><![CDATA[<h1>= Fax Application=</h1>]]></doctitle>
         <bottom><![CDATA[Copyright © 2011. All Rights Reserved.]]></bottom>
         <group title="util packages" packages="faxapp.util.*"/>
         <group title="web packages" packages="faxapp.web.*"/>
         <group title="data packages" packages="faxapp.entity.*:faxapp.dao.*"/>
      </javadoc>
   </target>

   <target name="usage">
      <echo message=""/>
      <echo message="${name} build file"/>
      <echo message="-----------------------------------"/>
      <echo message=""/>
      <echo message="Available targets are:"/>
      <echo message=""/>
      <echo message="deploy --> Deploy application as directory"/>
      <echo message="deploywar --> Deploy application as a WAR file"/>
      <echo message=""/>
   </target>


   <target name="build" description="Compile main source tree java files">
      <mkdir dir="${build.dir}"/>
      <javac destdir="${build.dir}" source="1.5" target="1.5" debug="true"
         deprecation="false" optimize="false" failonerror="true">
         <src path="${src.dir}"/>
         <classpath refid="master-classpath"/>
      </javac>
   </target>

   <target name="deploy" depends="build" description="Deploy application">
      <copy todir="${deploy.path}/${name}" preservelastmodified="true">
         <fileset dir="${web.dir}">
            <include name="**/*.*"/>
         </fileset>
      </copy>
   </target>

   <target name="deploywar" depends="build" description="Deploy application as a WAR file">
      <war destfile="${name}.war" webxml="${web.dir}/WEB-INF/web.xml">
         <fileset dir="${web.dir}">
            <include name="**/*.*"/>
         </fileset>
      </war>
      <copy todir="${deploy.path}" preservelastmodified="true">
         <fileset dir=".">
            <include name="*.war"/>
         </fileset>
      </copy>
   </target>

   <target name="clean" description="Clean output directories">
      <delete>
         <fileset dir="${build.dir}">
            <include name="**/*.class"/>
         </fileset>
      </delete>
   </target>
   <!-- ============================================================ -->
   <!-- Tomcat tasks -->
   <!-- ============================================================ -->

   <path id="catalina-ant-classpath">
   <!-- We need the Catalina jars for Tomcat -->
   <!-- * for other app servers - check the docs -->
      <fileset dir="${appserver.lib}">
         <include name="catalina-ant.jar"/>
      </fileset>
   </path>

   <taskdef name="install" classname="org.apache.catalina.ant.InstallTask">
      <classpath refid="catalina-ant-classpath"/>
   </taskdef>
   <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask">
      <classpath refid="catalina-ant-classpath"/>
   </taskdef>
   <taskdef name="list" classname="org.apache.catalina.ant.ListTask">
      <classpath refid="catalina-ant-classpath"/>
   </taskdef>
   <taskdef name="start" classname="org.apache.catalina.ant.StartTask">
      <classpath refid="catalina-ant-classpath"/>
   </taskdef>
   <taskdef name="stop" classname="org.apache.catalina.ant.StopTask">
      <classpath refid="catalina-ant-classpath"/>

   </taskdef>

   <target name="reload" description="Reload application in Tomcat">

      <reload url="${tomcat.manager.url}"username="${tomcat.manager.username}"
      password="${tomcat.manager.password}" path="/${name}"/>
   </target>
</project>

在本示例中,我们使用 Tomcat 作为我们的应用程序服务器。

In this example, we have used Tomcat as our application server.

首先,在构建属性文件中,我们定义了一些附加属性,如下所示 −

First, in the build properties file, we have defined some additional properties which are explained below −

  1. The appserver.home points to the installation path to the Tomcat application server.

  2. The appserver.lib points to the library files in the Tomcat installation folder.

  3. The deploy.path variable now points to the webapp folder in Tomcat.

Tomcat 中的应用程序可以通过 Tomcat 管理器应用程序停止和启动。管理员应用程序的 URL、用户名和密码同时也指定在 build.properties 文件中。

Applications in Tomcat can be stopped and started using the Tomcat manager application. The URL for the manager application, username and password are also specified in the build.properties file.

接下来,我们声明一个新的 CLASSPATH,其中包含 catalina-ant.jar 。通过 Apache Ant 执行 Tomcat 任务需要此 jar 文件。

Next, we declare a new CLASSPATH that contains the catalina-ant.jar. This jar file is required to execute Tomcat tasks through Apache Ant.

Tasks

catalina-ant.jar 提供了以下任务 −

The catalina-ant.jar provides the following tasks −

Sr.No

Properties & Description

1

InstallTask Installs a web application. Class Name: org.apache.catalina.ant.InstallTask

2

ReloadTask Reload a web application. Class Name: org.apache.catalina.ant.ReloadTask

3

ListTask Lists all web applications. Class Name: org.apache.catalina.ant.ListTask

4

StartTask1 Starts a web application. Class Name: org.apache.catalina.ant.StartTask

5

StopTask Stops a web application. Class Name: org.apache.catalina.ant.StopTask

6

ReloadTask Reloads a web application without stopping. Class Name: org.apache.catalina.ant.ReloadTask

重新加载任务需要以下附加参数:

The reload task requires the additional parameters which are as follows −

  1. URL to the manager application.

  2. Username to restart the web application.

  3. Password to restart the web application.

  4. Name of the web application to be restarted.

让我们发出 deploy-war 命令以将 Webapp 复制到 Tomcat Webapps 文件夹,然后让我们重新加载传真 Web 应用程序。以下结果是运行 Ant 文件的结果:

Let us issue the deploy-war command to copy the webapp to the Tomcat webapps folder and then, let us reload the Fax Web application. The following outcome is the result of running the Ant file −

C:\>ant deploy-war
Buildfile: C:\build.xml

BUILD SUCCESSFUL
Total time: 6.3 seconds

C:\>ant reload
Buildfile: C:\build.xml

BUILD SUCCESSFUL
Total time: 3.1 seconds

一旦运行了上述任务,Web 应用程序将部署并且 Web 应用程序将重新加载。

Once the above task is run, the web application is deployed and the web application is reloaded.

Ant - Executing Java code

您可以使用 Ant 来执行 Java 代码。在以下示例中,Java 类接收一个参数(管理员的电子邮件地址)并发送电子邮件。

You can use Ant to execute the Java code. In the following example, the java class takes in an argument (administrator’s email address) and send out an email.

public class NotifyAdministrator {
   public static void main(String[] args) {
      String email = args[0];
      notifyAdministratorviaEmail(email);
      System.out.println("Administrator "+email+" has been notified");
   }
   public static void notifyAdministratorviaEmail(String email {
      //......
   }
}

这是一个简单的构建,它执行该 Java 类。

Here is a simple build that executes this java class.

<?xml version="1.0"?>
<project name="sample" basedir="." default="notify">
   <target name="notify">
      <java fork="true" failonerror="yes" classname="NotifyAdministrator">
         <arg line="admin@test.com"/>
      </java>
   </target>
</project>

当构建执行时,它将生成以下结果:

When the build is executed, it produces the following outcome −

C:\>ant
Buildfile: C:\build.xml

notify: [java] Administrator admin@test.com has been notified

BUILD SUCCESSFUL
Total time: 1 second

在此示例中,Java 代码执行简单的操作,即发送电子邮件。我们可以使用内置于 Ant 任务中的任务来执行此操作。

In this example, the java code does a simple thing which is, to send an email. We could have used the built in the Ant task to do that.

但是,现在您有了想法,您可以扩展您的构建文件以调用执行复杂操作的 Java 代码。例如:加密您的源代码。

However, now that you have got the idea, you can extend your build file to call the java code that performs complicated things. For example − encrypts your source code.

Ant - Eclipse Integration

如果您已经下载并安装了 Eclipse,您几乎不用做任何事情就可以开始。Eclipse 与 Ant 插件捆绑在一起,开箱即用。

If you have downloaded and installed Eclipse already, you have very little to do to get started. Eclipse comes pre bundled with the Ant plugin, ready to use.

按照如下简单步骤,可将 Ant 集成到 Eclipse 中。

Follow the simple steps, to integrate Ant into Eclipse.

  1. Make sure that the build.xml is a part of your java project, and does not reside at a location that is external to the project.

  2. Enable Ant View by following Window → Show View → Other → Ant → Ant.

  3. Open Project Explorer, drag the build.xml into the Ant View.

您的 Ant 视口与此给定视口类似 −

Your Ant view looks similar to the one given below −

eclipse ant

点击 target,build/clean/usage 将使用 target 运行 Ant。

Clicking on the targets, build / clean / usage will run Ant with the target.

点击“传真”将执行默认 target - usage

Clicking "fax" will execute the default target - usage.

Ant Eclipse 插件还带有适合编辑 build.xml 的好编辑器。该编辑器了解 build.xml 架构并且可以帮助您完成代码。

The Ant Eclipse plugin also comes with a good editor for editing build.xml files. The editor is aware of the build.xml schema and can assist you with code completion.

要使用 Ant 编辑器,请右键单击您的 build.xml(从 Project Explorer 中),并选择用 > Ant Editor 打开。Ant 编辑器应类似于:

To use the Ant editor, right click your build.xml (from the Project Explorer) and select Open with > Ant Editor. The Ant editor should look something similar to −

ant editor

Ant 编辑器在右侧列出 target。target 列表用作书签,以允许您直接跳到特定 target 编辑中。

The Ant editor lists the targets on the right hand side. The target list serves as a bookmark that allows you to jump straight into editing a particular target.

Ant - JUnit Integration

JUnit 是基于 Java 开发的常用单元测试框架。它易于使用和扩展。有许多可用 JUnit 扩展。如果您不熟悉 JUnit,则应从 www.junit.org 下载它并阅读其手册。

JUnit is the commonly used unit testing framework for Java-based developments. It is easy to use and easy to extend. There are a number of JUnit extensions available. If you are unfamiliar with JUnit, you should download it from www.junit.org and read its manual.

本章介绍如何使用 Ant 执行 JUnit 测试。Ant 的使用通过 JUnit 任务变得简单。

This chapter shows how to execute JUnit tests by using Ant. The use of Ant makes it straight forward through the JUnit task.

JUnit 任务的属性如下所示 −

The attributes of the JUnit task are presented below −

Sr.No

Properties & Description

1

dir Where to invoke the VM from. This is ignored when fork is disabled.

2

jvm Command used to invoke the JVM. This is ignored when fork is disabled.

3

fork Runs the test in a separate JVM.

4

errorproperty The name of the property to set if there is a JUnit error.

5

failureproperty The name of the property to set if there is a JUnit failure.

6

haltonerror Stops execution when a test error occurs.

7

haltonfailure Stops execution when a failure occurs.

8

printsummary Advises Ant to display simple statistics for each test.

9

showoutput Advises Ant to send the output to its logs and formatters.

10

tempdir Path to the temporary file that Ant will use.

11

timeout Exits the tests that take longer to run than this setting (in milliseconds).

让我们继续 Hello World 传真 Web 应用程序的主题,并添加 JUnit 目标。

Let us continue the theme of the Hello World Fax web application and add a JUnit target.

以下示例显示了一个简单的 JUnit 测试执行 −

The following example shows a simple JUnit test execution −

<target name="unittest">
   <junit haltonfailure="true" printsummary="true">
      <test name="com.tutorialspoint.UtilsTest"/>
   </junit>
</target>

此示例显示在 com.tutorialspoint.UtilsTest junit 类上执行 JUnit。

This example shows the execution of JUnit on the com.tutorialspoint.UtilsTest junit class.

运行以上代码将产生以下输出 −

Running the above code produces the following output −

test:
[echo] Testing the application
[junit] Running com.tutorialspoint.UtilsTest
[junit] Tests run: 12, Failures: 0, Errors: 0, Time elapsed: 16.2 sec
BUILD PASSED

Ant - Extending Ant

Ant 附带一组预定义的任务,但是您可以创建自己的任务,如下例所示:

Ant comes with a predefined set of tasks, however you can create your own tasks, as shown in the example below.

自定义 Ant 任务应扩展 org.apache.tools.ant.Task 类并且应扩展 execute() 方法。

Custom Ant Tasks should extend the org.apache.tools.ant.Task class and should extend the execute() method.

以下是一个简单的示例 −

Below is a simple example −

package com.tutorialspoint.ant;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.BuildException;
public class MyTask extends Task {
   String message;
   public void execute() throws BuildException {
      log("Message: " + message, Project.MSG_INFO);
   }
   public void setMessage(String message) {
      this.message= message;
   }
}

如欲执行自定义任务,您需要将以下内容添加到 Hello World 传真 Web 应用程序 −

To execute the custom task, you need to add the following to the Hello World Fax web application −

<target name="custom">
   <taskdef name="custom" classname="com.tutorialspoint.ant.MyTask" />
   <custom message="Hello World!"/>
</target>

执行上述自定义任务将打印消息“Hello World!”

Executing the above custom task prints the message 'Hello World!'

c:\>ant custom
test:
[custom] Message : Hello World!
elapsed: 0.2 sec
BUILD PASSED

这仅是一个简单的示例。Ant 允许充分发挥其性能,助您提升构建和部署流程。

This is just a simple example. You can use the power of Ant to do whatever you want to improve your build and deployment process.

ANT - Using Token Filter

Ant 过滤器允许为当前项目设置一个标记过滤器。一个标记会用 @ 符号分隔,并且可以用属性文件读取。

Ant Filter allows to set a token filter for current project. A token is seperated by @ symbol and can be read using properties file as well.

Steps

  1. Step 1 − Define a token using @@.

This is a sample text written in @year@.
  1. Step 2 − Set the filter.

<filter token="year" value="2021"/>
  1. Step 3 − Use the filter. All tasks will replace the occurence of @year@ with 2021.

<copy todir="${dest.dir}" filtering="true">
   <fileset dir="${src.dir}"/>
</copy>

Filter Task Properties

以下是关键属性 −

Following are the key attributes −

Sr.No

Attribute & Description

1

token the token string without the separator chars (@)

2

value the string that should be put to replace the token when the file is copied.

3

filtersfile The file from which the filters must be read. This file must be a formatted as a property file.

为了让 Filter 任务正常工作,必须提供标记和值或过滤器文件。

Either token and value to be provided or filtersfile to Filter task to work properly.

Example

使用以下内容创建一个 src 文件夹和 text1.txt 文件 −

Create a src folder with text1.txt file with following contents −

This is a sample text written in @year@.

使用以下内容创建 build.xml −

Create build.xml with the following content −

<?xml version="1.0"?>
<project name="sample" basedir="." default="copy">
   <property name="src.dir" value="src"/>
   <property name="dest.dir" value="build"/>
   <target name="copy">
      <filter token="year" value="2021"/>
      <copy todir="${dest.dir}" filtering="true">
         <fileset dir="${src.dir}"/>
      </copy>
   </target>
</project>

Output

在上述构建文件上运行 Ant 会生成以下输出:

Running Ant on the above build file produces the following output −

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

copy:
   [copy] Copying 1 file to F:\tutorialspoint\ant\build

BUILD SUCCESSFUL
Total time: 1 second

F:\tutorialspoint\ant>

查看复制到 build 文件夹的文件的内容。

Verify the content of copied file to build folder.

This is a sample text written in 2021.

Ant - Using Command Line Arguments

Ant 可以轻松读取命令行参数,以便将数据传递给其任务。

Ant can read command line arguments easily to pass data to its tasks.

Commnd Line Arguments Options

ant [options] [target [target2 [target3] ...]]
Options:
   -help,          -h              print this message and exit
   -projecthelp,   -p              print project help information and exit
   -version                        print the version information and exit
   -diagnostics                    print information that might be helpful to diagnose or report problems and exit
   -quiet,         -q              be extra quiet
   -silent,        -S              print nothing but task outputs and build failures
   -verbose,       -v              be extra verbose
   -debug,         -d              print debugging information
   -emacs,         -e              produce logging information without adornments
   -lib          <path>            specifies a path to search for jars and classes
   -logfile      <file>            use given file for log
   -l            <file>                      ''
   -logger       <classname>       the class which is to perform logging
   -listener     <classname>       add an instance of class as a project listener
   -noinput                              do not allow interactive input
   -buildfile    <file>            use given buildfile
   -file         <file>                      ''
   -f            <file>                      ''
   -D            <property>=<value>   use value for given property
   -keep-going,    -k              execute all targets that do not depend on failed target(s)
   -propertyfile <name>            load all properties from file with -D properties taking precedence
   -inputhandler <class>           the class which will handle input requests
   -find         <file>            (s)earch for buildfile towards the root of
   -s            <file>            the filesystem and use it
   -nice         number            A niceness value for the main thread:1 (lowest) to 10 (highest); 5  is the default
   -nouserlib                      Run ant without using the jar files from ${user.home}/.ant/lib
   -noclasspath                    Run ant without using CLASSPATH
   -autoproxy                      Java 5+ : use the OS proxies
   -main         <class>           override Ant's normal entry point

我们将使用 -Dproperty 将变量传递给构建任务。

We’ll be using -Dproperty to pass varibles to the build task.

Example

使用以下内容创建一个 src 文件夹和 text1.txt 文件 −

Create a src folder with text1.txt file with following contents −

This is a sample text written in 2021.

使用以下内容创建 build.xml −

Create build.xml with the following content −

<?xml version="1.0"?>
<project name="sample" basedir="." default="copy">
   <target name="copy">
      <copy todir="${dest.dir}" filtering="true">
		<fileset dir="${src.dir}"/>
      </copy>
   </target>
</project>

Output

此处我们使用 src.dir 和 dest.dir 属性,但并未对其进行定义。我们将使用命令行参数来传递这些属性。在上述构建文件中运行 Ant 时,将生成以下输出 −

Here we’re using src.dir and dest.dir properties without defining them. We’ll pass them using command line arguments. Running Ant on the above build file produces the following output −

F:\tutorialspoint\ant>ant -Dsrc.dir=src -Ddest.dir=build
Buildfile: F:\tutorialspoint\ant\build.xml

copy:
   [copy] Copying 1 file to F:\tutorialspoint\ant\build
BUILD SUCCESSFUL
Total time: 0 seconds

F:\tutorialspoint\ant>

查看复制到 build 文件夹的文件的内容。

Verify the content of copied file to build folder.

This is a sample text written in 2021.

Ant - If Else Arguments

Ant 允许基于传递的条件来运行目标。我们可以使用 if 语句或 unless 语句。

Ant allows to run targets based on passed conditions. We can use if statement or unless statement.

Syntax

<target name="copy" if="copyFile">
   <echo>Files are copied.</echo>
</target>
<target name="move" unless="copyFile">
   <echo>Files are moved.</echo>
</target>

我们将使用 -Dproperty 将变量(如 copyFile)传递给构建任务。将要定义变量,此处变量的值无关紧要。

We’ll be using -Dproperty to pass varible like copyFile to the build task. The variable is to be defined, the value of variable is of no relevance here.

Example

使用以下内容创建 build.xml −

Create build.xml with the following content −

<?xml version="1.0"?>
<project name="sample" basedir="." default="copy">
   <target name="copy" if="copyFile">
      <echo>Files are copied.</echo>
   </target>
   <target name="move" unless="copyFile">
      <echo>Files are moved.</echo>
   </target>
</project>

Output

在上述构建文件上运行 Ant 会生成以下输出:

Running Ant on the above build file produces the following output −

F:\tutorialspoint\ant>ant -DcopyFile=true
Buildfile: F:\tutorialspoint\ant\build.xml

copy:
   [echo] Files are copied.

BUILD SUCCESSFUL
Total time: 0 seconds

F:\tutorialspoint\ant>ant move
Buildfile: F:\tutorialspoint\ant\build.xml

move:
   [echo] Files are moved.

BUILD SUCCESSFUL
Total time: 0 seconds

F:\tutorialspoint\ant>ant move -DcopyFile=true
Buildfile: F:\tutorialspoint\ant\build.xml

move:

BUILD SUCCESSFUL
Total time: 0 seconds

F:\tutorialspoint\ant>ant move -DcopyFile=false
Buildfile: F:\tutorialspoint\ant\build.xml

move:

BUILD SUCCESSFUL
Total time: 0 seconds

F:\tutorialspoint\ant>ant move -DcopyFile=true
Buildfile: F:\tutorialspoint\ant\build.xml

move:

BUILD SUCCESSFUL
Total time: 0 seconds

F:\tutorialspoint\ant>ant move
Buildfile: F:\tutorialspoint\ant\build.xml

move:
   [echo] Files are moved.

BUILD SUCCESSFUL
Total time: 0 seconds

F:\tutorialspoint\ant>

Ant - Custom Components

Ant 允许轻松创建和使用自定义组件。可通过实现 Condition、Selector、Filter 等接口来创建自定义组件。一旦类准备就绪,我们便可以使用 typedef 在 build.xml 内创建该组件,以便在任何目标下使用。

Ant allows to create and use custom components very easily. Custom Components can be created by implementing Condition, Selector, Filter etc. interfaces. Once a class is ready, we can use typedef to create the component within build.xml to be used under any target.

Syntax

首先,将一个类定义为 Ant 自定义组件,比如 TextSelector.java,然后在 build.xml 中定义一个选择器。

First define a class as Ant custom component say TextSelector.java then in build.xml, define a selector.

<typedef name="text-selector" classname="TextSelector" classpath="."/>

然后,在目标内使用该组件。

Then use that component within a target.

<target name="copy">
   <copy todir="${dest.dir}" filtering="true">
      <fileset dir="${src.dir}">
         <text-selector/>
      </fileset>
   </copy>
</target>

Example

使用以下内容创建 TextSelector.java,将其放置在与 build.xml 相同的位置 −

Create TextSelector.java with the following content and put the same in same place as build.xml −

import java.io.File;
import org.apache.tools.ant.types.selectors.FileSelector;
public class TextFilter implements FileSelector {
   public boolean isSelected(File b, String filename, File f) {
      return filename.toLowerCase().endsWith(".txt");
   }
}

在 src 目录中创建一个 text1.txt 和一个 text2.java。目标是将仅 .txt 文件复制到构建目录。

Create a text1.txt and a text2.java in src directory. Target is to be copy only .txt file to build directory.

使用以下内容创建 build.xml −

Create build.xml with the following content −

<?xml version="1.0"?>
<project name="sample" basedir="." default="copy">
   <property name="src.dir" value="src"/>
   <property name="dest.dir" value="build"/>
   <typedef name="text-selector" classname="TextSelector"  classpath="."/>
   <target name="copy">
      <copy todir="${dest.dir}" filtering="true">
         <fileset dir="${src.dir}">
            <text-selector/>
         </fileset>
      </copy>
   </target>
</project>

Output

在上述构建文件上运行 Ant 会生成以下输出:

Running Ant on the above build file produces the following output −

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

copy:
   [copy] Copying 1 file to F:\tutorialspoint\ant\build

BUILD SUCCESSFUL
Total time: 0 seconds

现在仅复制 .txt 文件。

Now only .txt file is copied.

Ant - Listeners & Loggers

Ant 允许使用侦听器和记录器监控构建过程。

Ant allows the build process to be monitored using listeners and loggers.

Listeners

Ant 提供以下事件,可以使用侦听器捕获这些事件。

Ant provides following events to be captured using listeners.

  1. build started

  2. build finished

  3. target started

  4. target finished

  5. task started

  6. task finished

  7. message logged

可以使用 -listener 参数在命令行上注册自定义侦听器。

Custom listeners can be registered on command line using -listener argument.

Loggers

记录器扩展了侦听器的功能,并添加了以下特性

Loggers extends listeners capabilities and add the following features

  1. Can log information to console or file using -logfile argument

  2. Can log using logging levels like -quiet, -verbose, -debug

  3. Are emacs-mode aware

Built-in Listeners/loggers

  1. org.apache.tools.ant.DefaultLogger − The logger used implicitly unless overridden with the -logger command-line switch.

  2. org.apache.tools.ant.NoBannerLogger − This logger omits output of empty target output.

  3. org.apache.tools.ant.listener.MailLogger − Extends DefaultLogger such that output is still generated the same, and when the build is finished an e-mail can be sent.

  4. org.apache.tools.ant.listener.AnsiColorLogger − Colorifies the build output.

  5. org.apache.tools.ant.listener.Log4jListener − Passes events to Apache Log4j for highly customizable logging.

  6. org.apache.tools.ant.XmlLogger − Writes the build information to an XML file.

  7. org.apache.tools.ant.TimestampedLogger − Prints the time that a build finished

  8. org.apache.tools.ant.listener.BigProjectLogger − Prints the project name every target

  9. org.apache.tools.ant.listener.SimpleBigProjectLogger − Prints the project name for subprojects only, otherwise like NoBannerLogger Since Ant 1.8.1

  10. org.apache.tools.ant.listener.ProfileLogger − The default logger, with start times, end times and durations added for each task and target.

Example

使用以下内容创建 build.xml:

Create build.xml with the following content:

<?xml version="1.0"?>
<project name="sample" basedir="." default="copy">
   <target name="copy">
     <echo>File Copied</echo>
   </target>
</project>

Output

在上述构建文件上运行 Ant 会生成以下输出:

Running Ant on the above build file produces the following output −

F:\tutorialspoint\ant>ant -logger org.apache.tools.ant.listener.TimestampedLogger
Buildfile: F:\tutorialspoint\ant\build.xml

copy:
   [echo] File Copied

BUILD SUCCESSFUL - at 03/12/21, 11:24 AM
Total time: 0 seconds

F:\tutorialspoint\ant>ant -logger org.apache.tools.ant.XmlLogger -verbose -logfile build_log.xml
Apache Ant(TM) version 1.10.12 compiled on October 13 2021
Trying the default build file: build.xml
Buildfile: F:\tutorialspoint\ant\build.xml

现在,你可以检查 build_log.xml 文件是否已使用相关日志创建。

Now you can check build_log.xml file is created with relevant logs.