Jakarta Commons: Use Class and Components 1 (2)

zhaozj2021-02-16  62

Jakarta Commons: Using class and component 1 (2) Author: Vikram Goyal; cactus studio Translation dispatch time: 2003.08.07 15:33:09 using such methods what good is it? 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.itrator; public final class office ontv extends enum {public static final ontv idol = new ONTV ( "Idol"); public static final ontv survivor = new office "); 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 getEnumMap () {return getEnumMap (OnTV.class) } Public static list genumlist () {return genumlist (ontv.class);} public static iterator itrator () {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 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. Compared to Java standard implementation, 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 in a limited article space, but here 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 (); // ... // adds the element to the HeapHeap.Add (new integer (-1)); Heap.Add (New Integer (10)); Heap.Add (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 the parameter / / specifies NullcomParetor. NullComparator compare // null and other objects, according to NullsareHigh tags // Judgment NULL value is large or small than other objects: If // nullsarehigh is false, it is considered that NULL is smaller than // other objects. 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 more than other objects small. Heap2.remove (); Introduction to other COMMONS components is over here. If you want to know more details, see the API document, it is best to 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 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 both files, there is another normal text input box:

Enter your name:

graphic:
file:


Create a JSP page.

// ... // 1 Check the input request to be a form data for Multipart. Boolean ismultipart = fileupload. ismultipartContent (Request); // ... // 2 Create a handle for the request, parsing the request. After performing // parsing, all form items are saved in a list. DiskfileUpload Upload (); // The request is parsed by handle, the resulting item is saved in a list items = UPLOAD.PARSEREQUEST (REQUEST); / / ... // 3 sequentially obtain the file item inside the list. To distinguish items indicating // files and normal form input items, use the isformfield () // method. Depending on the request of the processing request, we can save the uploaded text //, or one byte of one byte handles the file content, or the input stream of the file. Iterator itr = items.iterator ();

While (itr.hasnext ()) {fileItem item = (fileItem) ITR.Next (); // Check the current item 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 field is Name ... if (FieldName.Equals ("name")) Request.settribute ("MSG", "Thank you:" item. GetString ());} Else {// The project is an uploaded file and saves it to disk. // Note that 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 (getRealPath ("/"), fullfile.getname (); item.write (savedfile);} We can upload The UPLOAD.SETSIZEMAX of the handle is limited to the size of the upload file. 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-19778.html

New Post(0)