Jakarta Commons: Use class and components Jakarta Commons are Jakarta sub-projects, which creates and maintains many independent packages, which are generally with other frameworks or products.
Norway, a large number of small, practical components are collected, and most of them are programmed for server-side.
The package of Commons is divided into two parts: Sandbox, the Commons Code Base. Sandbox is a test platform for verifying various ideas.
plan. The components introduced in this article belong to the Commons Code Base. The article will show the functions, applicable occasions of each component, and through simple example
Introduce its usage.
I. Overview
Reusability is the soul of the Jakarta Commons project. These packages have considered a reusability problem in the design phase. among them
Some packages, such as the logging package used to record the logs, which is originally designed for other projects, such as Jakarta Struts.
Project, when people discovering that these packages are also very useful for other projects, they can greatly help other projects, they decided to be these packages.
Construct a "public" storage location, this is the Jakarta Commons project.
In order to truly improve reusability, each package must not depend on other large frames or projects. Therefore, the package of the Commons project
It is basically independent, not only to independence with other projects, but also independent of most other packages inside the Commons. although
There are some exceptions, such as the BaETWixT package to use the XML API, but most of them use the most basic API, the main purpose
It is necessary to be able to easily call via a simple interface.
However, due to the brief admiral, many packages have become too simple, lack maintenance and support, even some of the wrong links,
The document is also very poor. Most packages need us to find out their usage, and sometimes we need to analyze their applicable occasions.
This article will introduce these packages one by one, hoping to help you quickly master this free code base that has accumulated many people.
Note: Jakarta Commons and Apache Commons are different, the latter is one of Apache Software Foundation.
The top project, the former is a sub-project of the Jakarta project, and the protagonist to be discussed herein. This article is mentioned in Commons
Wherever the place, Jakarta's Commons.
In order to facilitate explanation, this article divides the 18 finished components of the Commons project (excluded EL, LATKA and JEXL) into Type 5.
As shown in the following table.
It must be pointed out that this classification is only for the convenience of the article, and there is no such classification in the Commons project.
There is sometimes a certain overlap between these categories.
This article first introduces the components in the Web related class and other classes, the next article will involve XML related, packaging these two categories, the last one
The article specifically introduces a package that belongs to the tool class.
Second, other classes
CLI, Discovery, Lang and Collectes are incorporated into other classes, because they are all for a certain, practical
Small goals can be described as decentralized.
2.1 CLI
■ Overview: CLI, Command Line Interface, is also "command line interface", it is accessible and parsing the command line for Java programs
The parameters provide a unified interface.
■ Official resources: home page, binary, source code
■ When you apply: When you need to access the command line parameters in a unified manner.
■ Example App: Clidemo.java. Commons-cli-1.0.jar must be included in ClassPath. ■ Description:
How many times you have to redesign a new command line parameter processing method for a new application? If you can only use a single one
Interface, uniform completion, such as defining input parameters (whether it is forced parameters, numerical or strings, etc.), according to a series of rule analysis
Parameters, determine the task such as the path to be used, then how good! The answer is in the CLI.
In the CLI, each of the parameters you want to specify in the command is an Option object. First create an Options object, will
Each Option object adds to an Options object, and then uses the method provided by the CLI to resolve the user's input parameters. Option object
The user must enter a parameter, such as the file name must be provided on the command line. If a parameter is necessary, create an Option pair
It is necessary to explicitly specify when it is like.
Here is the steps using the CLI.
// ...
// 1 Create a Options:
Options options = new options ();
Options.addoption ("T", False, "Current Time");
// ...
// 2 Create a parser and analyze the input:
CommandLineParser Parser = New BasicParser ();
CommandLine CMD;
Try {
CMD = Parser.Parse (Options, Args);
} catch (parseException pe) {
USAGE (Options);
Return;
}
// ...
// 3 Finally, according to the user's input, take the corresponding operation:
IF (cmd.hasoption ("n")) {
System.err.println ("Nice to meet you:"
CMD.GetoptionValue ('n'));
}
This is the complete process using the CLI. Of course, the CLI provides other advanced options, such as control formats and parsing processes, etc.
But basic use ideas is still consistent. See the sample program provided in this article.
2.2 Discovery
■ Overview: Discovery Components is an implementation of discovery pattern, its goal is to follow a unity
Ways positioning and instantiating classes and other resources.
■ Official resources: home page, binary, source code.
■ When applies: When you want to use the best algorithm to find various implementations of the Java interface in the Java program.
■ Application example: DiscoveryDemo.java, MyInterface.java, MyImpl1.java, MyImpl2.java, MyInterface.
It is required to include Commons-Discovery.jar and Commons-Logging.jar in ClassPath.
■ Description:
Discovery means "discovery", it tries to find all known implementations of an interface with the best algorithm. Service
In addition, the Discovery component is especially useful when we want to find all known providers of a service.
Consider this situation: We wrote an interface for a particularly complex task, all the implementations of the interface are different.
The way this complex task is completed, and the end user can select the specific way to complete the task as needed. Then, in this case, what should the end user use to find all the available implementations of the interface (ie possible way to complete the task)?
The situation described above is the so-called service-service provider system. The function of the service is described by the interface, and the service provider provides specific
Realization. The current problem is that end users should use some way to find which service providers have installed in the system. In this case,
The Discovery component is useful, but it can not only find classes that implement specific interfaces, but also to find resources.
For example, a picture or other file, etc. DISCOVERY follows the rules defined by the Sun's service provider system when performing these operations.
For this reason, the use of Discovery components really brings a lot of convenience. Please read the interface to the interface in the sample program in this article
MyInterface.java and two implementation class MyImpl1.java, MyIMple2.java, learn the details of the following example. Use discovery
When you provide myInterface file, put it into the meta-inf / service directory, pay attention to the full interface of the file.
The Fully Qualified Name, if the interface belongs to a package, the name of the file must also change accordingly.
// ...
// 1 Create an instance of a class equipment.
ClassLoaders loadingers =
ClassLoaders.Getapploaders (MyInterface.class, getClass (), FALSE;
// ...
// 2 Use discoverclass to find the implementation class.
Discoverclass Discover = New DiscoverClass (loadingers);
// ...
// 3 Find the class that implements the specified interface:
Class Implclass = discover.find (MyInterface.class);
System.err.Println ("Implementing Provider:" Implclass.getName ());
Run the above code, you can get the class registered in the MyInterface file. Remind again, if your implementation is packaged in the package
Inside, the name registered here should also be modified accordingly, if the file is not placed in the correct position, or the implementation of the name
The class cannot be found or instantiated, and the program will throw discoverexception, indicating that the eligible implementation is not found. Here is MyInterface
An example of the file content: MyImpl2 # Implementation 2.
Of course, the registration method for realizing the class is not only one, otherwise the practicality of Discovery is a big discount! In fact,
Follow the Class search mechanism within Discovery, the class registered according to this method will be the final found in Discovery. Another common
The registration method is to pass the name of the implementation class through system properties or user-defined properties, for example, give up
Meta-inf / service
The file is changed to execute the java -dmyinterface = myImpl1 discoveryDemo command to run sample programs, the system properties here
It is the name of the interface, the value is the provider of the interface, and the result of the run is exactly the same.
Discovery can also be used to create a SINGLETON instance and call its method, the syntax is as follows:
(MyInterface) discover.newinstance (MyInterface.class)). Mymethod () ;. Note In this example, we don't know which service provider has implemented myMethod, and even we don't have to care at all. Specific situation and run this paragraph
The way the code is registered in the operating environment, and the active service is available in different environments.
Perspective may be different.
2.3 lang
■ Overview: LANG is an extension package of java.lang, adds a number of operation String features, and also supports the amount of enumeration in C.
■ Official resources: home page, binary, source code.
■ When applies: When the method provided by the java.lang package does not meet the needs, you want more features to handle string, value, and
When the System property; also, when you want to use a C style enumeration amount.
■ Sample application: langDemo.java, Mortgage.java, Ontv.java. Commons-lang.jar must be included in ClassPath.
■ Description:
This package provides a number of methods provided for convenient purposes, most of them are static, simplified daily encoding.
The Stringutils class is one of the representatives that make developers can deal with the standard Java.lang.String package to process strings.
Using these methods is simple, usually as long as the appropriate parameters are provided when calling a static method. For example, if you want a word
The first character is changed to uppercase, simply call: StringUtils.capitalise ("name"), the output result called the called is Name. Please browse
StringUtils API documentation understands other static methods, maybe you will find some code that can be used directly. Examples provided herein
The program demonstrates the use of some of these methods.
Another worthless class is randomstringutils, which provides a method of generating a random string to create a random relative
It is too convenient.
The NumberUtils class provides a method of processing numerical data. Many methods are worthwhile, such as looking for maximum, minimum methods, will
String is converted into a numerical method, and so on. NumberRange and Charrange class provide creation and operating numerical ranges, word symbols
Method.
The class in the Builder package provides some special methods, which can be used to construct a class of Tostring, Hashcode, Compareto and Equals.
Method, its basic idea is to construct high quality Tostring, Hashcode, Compareto, and Equals methods, thereby eliminating
The user defines these methods, as long as the method in the Builder package is called. For example, we can use
TostringBuilder to construct the TOSTRING description of the class, as shown in the following example:
Public class mortgage {
PRIVATE FLOAT RATE;
Private int years;
....
Public string toString () {
Return New TostringBuilder (this).
Append ("rate", this.rate).
Append ("Years", this.Year.
Tostring ();
}
}
What is the benefit of using this type of method? Obviously, it makes us possible to handle all data types in a unified manner. all
The usage of the Builder method is similar to the above example.
Java does not have a C style enumeration. To this end, the lang package provides a type of secure ENUM type and fills the blank. The Enum class is abstract. If you want to create an enumeration, you will extend the Enum class. The following example clearly illustrates the use of Enum.
Import org.apache.commons.lang.enum.enum;
Import java.util.map;
Import java.util.list;
Import java.util.iterator;
Public Final Class Ontv Extends Enum {
Public Static Final ONTV IDOL =
NEW ONTV ("IDOL");
Public Static Final ONTV SURVIVOR =
New ONTV ("Survivor");
Public Static Final ONTV SEINFELD =
New ONTV ("Seinfeld");
Private ONTV (String Show) {
Super (show);
}
Public Static ONTV GETENUM (STRING SHOW) {
Return (ONTV) Getenum (onTv.class, Show);
}
Public static map geternal mapp () {
Return getenummap (palv.class);
}
Public static list genumlist () {
Return genumlist (ontv.class);
}
Public static iterator iterator () {
Return Iterator (ONTV.CLASS);
}
}
In the future, we can use the enumerated variables as follows: ONTV.GETENUM ("Idol"). This call from the enumeration data created in front
Type Returns IDOL. This example is relatively simple. In fact, the ENUM class also provides many useful methods, see later provided later.
Complete instance.
2.4 Collectes
■ Overview: Extension the Java Collection framework, add new data structures, iterative mechanisms, and comparison operators.
■ Official resources: home page, binary, source code.
■ When applies: Almost all important Java development projects that need to operate data structures can use the Collections API. Java
Compared to the standard implementation, the Collections API has many advantages.
■ Sample application: CollectionsDemo.java. Require ClassPath contains commons-collections.jar.
■ Description:
It is too difficult to introduce the Collections API to be more difficult to introduce the Collections API within a limited article. However, it will still cover most.
The most important class, I hope to cause your interest and carefully understand the rest of the class. Collectes itself has a lot of money.
The usage of each class is explained.
The BAG interface extension standard Java Collection allows the generator to track all elements in BAG. When you want to track
BAG is very useful when entering and exiting an element of an element. Since the Bag itself is an interface, actually use
Should be real
The class of this interface, such as Hashbag or Treebag - from these classes, it can also be seen that Hashbag implements a
Hashmap's Bag, while Treebag is realized by TreeMap's BAG. Two most important methods in the BAG interface are:
GetCount (Object O),
Used to return the number of occurrences of specific objects in BAG; uniqueSet (), returns all unique elements.
The Buffer interface allows the object in the collection in the predefined order, and the deletion may be LIFO (Last In First Out,
Afterwards, first out), or FIRST IN First Out, advanced first out, and can also be custom order. Let's take a look
How to implement a buffer, delete elements in the natural order.
The BinaryHeap class implements the buffer interface that can be deleted in the natural order. If you want to reverse the order, you must be in turn
False telling Heap to use the inverse order of the natural order.
BinaryHeap Heap = new binaryheap ();
// ...
// Add the elements to this Heap
Heap.add (new integer (-1));
Heap.add (new integer (-10));
Heap.add (new integer (0));
HEAP.ADD (New Integer (-3));
HEAP.ADD (New Integer (5));
// ...
/ / Delete an element
HEAP.Remove ();
Remove of the Heap, according to the natural order, -10 in the elements will be deleted. If we ask for sorting in advance,
The deleted will be 5.
FastArrayList, FasthashMap, and FastTreeMap classes can be operated in two modes, beyond the standards corresponding to them.
COLLECTION. The first mode is "slow mode", the class modification operation (added, deleted element) is synchronized. Relative to this, another mode
Is "fast mode", the access to these classes is defined as a read-only operation, so it is not necessary to synchronize, the speed is faster. In fast mode, structural changes
Complete by the following manner: First cloning the existing class, modify the cloned class, and finally replaced the original class with the cloned class.
FastArrayList, FasthashMap, and FastTreeMap classes are particularly suitable for most operations after initialization.
Multi-threaded environment.
The Iterator package provides a variety of collections and objects to provide an iterator provided by the standard Java Collection package. The sample application of this article is demonstrated.
Arrayiterator, access the contents of Array through iteration. The usage of various iterators in the ITERATORS package basically and standards
Java iterator is the same.
Finally, the Comparators package provides some practical comparison. The so-called comparators are actually a class, which defines how to compare
Two objects belonging to the same class determine their sorting order. For example, in the Buffer class mentioned earlier, we can define your own
The comparison is used to determine the order of the elements with a custom comparison. Rather than adopting the natural sort order of elements. Let's take a look at the specific
It has been achieved.
// ...
// 1 Create a BinaryHeap class, but this time
// Specify NullcomParetor. Nullcomparator
// null and other objects, according to Nullsarehigh tag
/ / Judgment NULL value is larger than other objects: if
// nullsarehigh's value is false, it is considered to be more than
// Other objects are small.
BinaryHeap Heap2 = New BinaryHeap
NEW NULLCOMPARATOR (FALSE);
// ...
// 2 Add some data (including several null values) to Heap: Heap2.Add (NULL);
Heap2.add (New Integer ("6"));
Heap2.Add (New Integer ("- 6"));
HEAP2.ADD (NULL);
// ...
// 3 finally delete an element, the NULL containing the BAG will decrease
//, because NULL is smaller than other objects.
Heap2.remove ();
The introduction of other class Commons components is ended here. If you want to know more details, please see the API document, the best
Take a look at the source code of these packages.
Third, Web class
The Web class components are used to perform tasks related to the web.
3.1 FileUpload
■ Overview: A file that can be used directly upload components.
■ Official Resources: Home. Since this component has not been officially released, there are many BUG released in February this year, so it is recommended
Download the latest version from Nightly Builds.
■ When applies: When you want to add an easy-to-use, high-performance file uploading components in the Java server environment.
■ Example App: FileUploadDemo.jsp, fileuploadDemo.htm, and msg.jsp. Require server-side application directory
Web-INF / LIB has commons-fileupload-1.0-devons-fileupload-1.0-dev.jar.
■ Description:
The FileUpload component solves the common file upload problem. It provides an easy-to-use interface to manage files uploaded to the server.
Can be used in JSP and servlets. FILEUPLOAD component complies with RFC1867, it analyzes input requests, providing a series of supplies to the application
Document to the server. Uploaded files can be retained in memory, or they can be placed in a temporary position (allowing configuring a representation of the file.
Small parameters, if the uploaded file exceeds the size specified by this parameter, write the file into a temporary location). There are also some parameters
Alternative, including acceptable maximum files, location of temporary files, etc.
Here is the steps to use the FileUpload component.
First create an HTML page. Note that all forms to upload files must set the encType property, and the value of the attribute must
Is Multipart / Form-Data, and the requesting method must be POST. The following form is in addition to the two files, there is another ordinary
Text input box: