Jakarta Commons: Use Class and Components 1 (2)

xiaoxiao2021-03-06  42

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 BUILDER methods are 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 returns IDOL from the enumeration data type created in front. This example is relatively simple. In fact, the ENUM class also provides a number of useful methods, see the complete instances provided later in this article. 2.4 Collections ■ Overview: Extension 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. Compared to Java standard implementation, Collections API has many advantages. ■ Sample application: CollectionsDemo.java. Require ClassPath contains commons-collections.jar. ■ Description: To introduce the Collections API in detail within a limited article level, it will still cover most of the most important classes, hoping to cause your interest, and carefully understand the rest of the class. The documentation of Collectes itself also provides many data and explains usage of each class. The BAG interface extension standard Java Collection allows the generator to track all elements in BAG. BAG is very useful when you want to track the total number of elements of a collection. Since the BAG itself is an interface, the actual use should be a class that implements the interface, such as Hashbag or Treebag - from these classes, it can also be seen that Hashbag implements a HashMap's BAG, and Treebag is implemented. Treemap Bag. The two most important ways in the BAG interface are: getCount (Object O), used to return the number of times of specific objects in BAG; uniqueSet (), returns all unique elements. The buffer interface allows the object in the collection in the predefined order, the delete order can be LIFO (Last In First Out, the first out), or FIFO (First In First Out, advanced first out), and it can also be customized. order. Let's take a look at how to implement a buffer, delete the element according to 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 pass a FALSE to tell HEAP to adopt a 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 reverse sequence, it will be 5. FastArrayList, FasthashMap, and FastTreeMap classes can be operated in two modes, beyond the standard Collection corresponding to them. The first mode is "slow mode", the class modification operation (added, deleted element) is synchronized. On the other hand, another mode is "fast mode", and 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 are completed in the following manner: First cloning the existing class, modify the cloned class, and finally replaced the original class with the cloning class. FastArrayList, FasthashMap, and FastTreeMap classes are particularly suitable for the most operations after initialization. Multi-threaded environments for read-only operations. 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 demonstrates ArrayItemrator, and accesses the contents of Array through iteration. The usage of various iterators in the ITERATORS package is basically the same as the standard Java iterator. Finally, the Comparators package provides some practical comparison. The so-called comparison is 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 comparison, with a custom comparison to determine the ordering order of the elements, rather than adopting the natural sort order of elements. Let's take a look at the specific implementation. // ...

// 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, see the API document, it is best to look at the source code for these packages. Third, the components of the Web class web class 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 yet been officially released, there are many BUGs released in February this year, so it is recommended to 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 a 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, which can be used in JSP and servlets. FileUpload Components Follow the RFC1867, which analyzes the input request, and provides a series of files uploaded to the server to the application. Uploaded files can be retained in memory, or they can be placed in a temporary location (allowing parameters that represent file size, if the uploaded file exceeds the size specified by this parameter, write a temporary position). There are also some parameters to be configured, including acceptable maximum files, location of temporary files, and more. Here is the steps to use the FileUpload component. First create an HTML page. Note that all forms to upload files must set an encType property, and the value of the attribute must be Multipart / Form-Data, and the requesting method must be POST. The following form except for the two files, there is an ordinary text input box:

Method = "post" encType = "multipart / form-data">

Enter your name:


Graphics:

Document:



Value = "Submit your file" />

Next, create a JSP page.

// ...

// 1 Check whether the input request is form data for Multipart.

Boolean ismultipart = fileupload.

IsmultipartContent (Request);

// ...

// 2 Create a handle for the request, parsing the request. carried out

// After analysis, all form items are saved in a list.

DiskfileUpload Upload ();

// Pass the request by handle, parsing the resulting item is saved in a list items = UPLOAD.PARSEREQUEST (Request);

// ...

// 3 The file item inside List is obtained in turn through the loop. To distinguish

// Project and normal form input items, use isformfield ()

// method. According to the requirements of the processing request, we can save uploaded texts

// piece, or one byte one byte handles file content, or play

// Open the input stream.

Iterator itr = items.iterator ();

While (itr.hasnext ()) {

FILEITEM ITEM = (fileItem) ITR.NEXT ();

// Check the current project is a normal form element, or an uploaded file

IF (item.isformfield ()) {

/ / Get the name of the form field

String FieldName = item.getfieldname ();

// If the name of the form is Name ...

IF (FieldName.equals ("Name"))

Request.setattribute ("msg",

"Thank you:" item.getstring ());

} else {

/ / The project is an uploaded file and saves it to disk.

// Note item.getname ()

// will return the full path name of the upload file on the client, which seems to be a bug.

/ / To solve this problem, FullFile.getName () is used here.

FILE FULLFILE = New File (item.getname ());

File SavedFile = New File

(GetServletContext (). getRealPath ("/"),

Fullfile.getname ());

Item.write (SavedFile);

}

}

We can limit the size of upload files by uploading UPLoad.setsizemax. When the size of the file exceeds the allowable value, the program will encounter an exception. In the above example, the limit value of the file size is -1, indicating that the file allowed to be loaded with analogize. There are other other forms of use, as indicated earlier, we can open a input stream on the uploaded file, or let them reside in memory until the space occupies a certain limit value, or in judging files On the basis of the type, the content is obtained in the form of a string or byte array, or the file is deleted directly. All this can be easily achieved using the method provided by the FileItem class (DefaultFileItem is an implementation of FileItem).

转载请注明原文地址:https://www.9cbs.com/read-72763.html

New Post(0)