JAKARTA COMMONS: Use class and components

zhaozj2021-02-16  60

JAKARTA Commons Project Group introduces Jakarta Commons: Class and Components Jakarta Commons are Jakarta subprojects, which creates and maintains many independent software packages, which are generally independent of other frameworks or products, which collect a large number of small, practical components. Most of the server-side programming. The package of Commons is divided into two parts: Sandbox, the Commons Code Base. Sandbox is a test platform for verifying various ideas, planning. The components introduced herein belong to the Commons Code Base. The article will show the functions of each component, applicable, and introduce the usage by a simple example. 1. Overview Reusability is the soul of the Jakarta Commons project. These packages have considered a reusability problem in the design phase. Some of these packages, such as the logging package used to record the logs, which is originally designed for other projects, such as Jakarta Struts projects, and it is very useful for other projects to greatly help other projects. Decide to construct a "public" storage location for these packages, 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 is basically independent, not only independent of other projects, but also independent of most of the other packages inside Commons. Although there are some exceptions, such as the BetwixT package is used to use the XML API, but most of them use the most basic API, the main purpose is to be able to easily call through simple interfaces. However, due to the brilliance, 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 a top project of Apache Software Foundation, the former is Jakarta

A sub-project of the project is also the protagonist to be discussed herein. Behind this article refers to 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 a 5 class, 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, and the boundaries of these categories sometimes have a certain overlap. This article first introduces the components of the Web related category and other classes. The next article will involve XML-related, packaging these two categories, and the last article specializes in the tool class. Second, other classes CLI, Discovery, Lang and Collections are incorporated into other classes, because they are all desirable for a clear, practical small goal, can be described as decentralized. 2.1 CLI ■ Overview: CLI is Command Line Interface, which is the "command line interface", which provides a unified interface for Java program access and parsing command line parameters. ■ Official resources: home page, binary, source code ■ When you apply: When you need to access 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 unify only a single interface, unify the input parameters (whether it is forced parameter, value or string, etc.), according to a range of rule analysis parameters, determine the path to the path to use, then it is 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, add each Option object to the Options object, and then use the method provided by the CLI to resolve the user's input parameters. Option objects may require a user to enter a parameter, such as the file name must be provided on the command line. If a parameter is a must, it is necessary to explicitly specify when creating an Option object. Here is the steps using the CLI. // ... // 1 Create an options: options options = new options (); Options.addoption ("t", false, "current time"); // ... // 2 Create a parser, analyze input: CommandLineParser Parser = New BasicParser (); CommandLine CMD; Try {cmd = parser.parse (options, args);} catch (optionption pE) {usage (options); Return;} // ... // 3 Finally, according to user 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, but basic use ideas are still consistent. See the sample program provided in this article.

2.2 Discovery ■ Overview: Discovery Components is an implementation of Discovery Pattern, which is to locate and instantiate classes and other resources in a unified manner. ■ 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. In the case of the service, the Discovery component is especially useful when we want to find all known providers of a service. Consider this situation: We have written an interface for a particularly complex task. All the implementations of the interface are done in different ways to complete this complex task, and end users can choose 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 a specific implementation. 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, such as images or other files. 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 reader to see the interface in the sample program in this article. MYINTERFACE.JAVA

And two implementation class MyImpl1.java, MyIMple2.java, learn about the details of the following examples. When using Discovery, you should put it in the meta-inf / service directory, pay attention to the full qualified name of the file corresponding to the interface, if the interface belongs to a package, the name of the file is also It must be changed accordingly. // ... // 1 Create an instance of a class loader. ClassLoaders Loaders = ClassLoaders.GetApploaders (MyInterface.class, getClass (), false); // ... // 2 Use discoverclass instance to find the implementation class. DiscoverClass discover = new DiscoverClass (loaders); // ... // ③ lookup implements the specified interface class: 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 that if your implementation is in the package, the name registered here should also be modified accordingly. If the file is not placed in the correct location, or the implementation class of the specified name cannot be found or instantiated, the program will Throw discoverexception, indicating that the implementation of the eligible condition is not found. Below is an example of the content of MyInterface file: 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, according to the class finding mechanism within Discovery, the class registered according to this method will be the Class finally found by Discovery. Another commonly used registration method is to pass the name of the implementation class through the system attribute or user-defined attribute, for example, abandon the file in the meta-inf / services directory, change the java -dmyinterface = myImpl1 discoveryDemo command to run the sample program The system attribute here 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 situations are related to operating this code and what service provider has been registered in the operating environment, running in different environments, the actual service provider may vary. 2.3 LANG ■ Overview: Lang is an extension package of java.lang, adds a number of operations of String, and also supports C-style enumerations.

. ■ Official resources: home page, binary, source code. ■ When applies: When the method provided by the java.lang package is not met, you want more features to handle String, value, and system properties; and if you want to use C style enumerations. ■ 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 to change a word's first character to uppercase, simply call: StringUtils.capitalise ("name"), the output result called the call is Name. Please browse the StringUtils API document to learn other static methods, maybe you will find some code that can be used directly. The sample program provided herein 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 password is too convenient. The NumberUtils class provides methods for processing numerical data. Many methods are worthwhile, such as finding the maximum, minimum method, converts String to a numerical method, and so on. The NumberRange and the Charrange class provide a way to create and operate numerical ranges, and character ranges. The class in the Builder package provides some special methods, which can be used to construct the Tostring, Hashcode, Compareto and Equals methods. Its basic ideas is to construct high quality Tostring, Hashcode, Compareto, and Equals methods, The user defines these methods, as long as the method in the Builder package is called. For example, we can use TostringBuilder to construct a class TSTRING description, 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 ();}} Is there any benefit to use 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.itrator; public final class office 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 office (String Show) {super (show);} public static ONTV Getenum (OnTv.class, show);} public static map genummap () {return genummap (ontv.class);} public static list getenumlist () {return genumlist (ontv.class); } public static iterator itrator () {return iterator;} After 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 (); // ... // 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 (); call the HEAP Remove, according to the natural order, element The -10 in the collection 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 this way, another model

The formula is "fast mode", which is a read-only operation for these types of access, 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, 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 uploading two files, there is another normal text input box:

Enter you Name:

graphic:
< Br /> file:


Create a JSP page next. // ... // 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 is Name ... if (FieldName.Equals ("name")) Request.setttribute ("msg" , "Thank you:" item.getstring ());} else {// This item 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). 3.2 HTTPCLIENT ■ Overview: This API extends the Java.net package, providing the function of the analog browser. ■ Official resources: home page, binary, source code. ■ When applies: When you want to construct a web browser; when your application needs an efficient way to communicate with HTTP / HTTPS communication. ■ Example Application: httpclientDemo.java. It is required to have commons-httpclient.jar in ClassPath, Common-logging.jar. Requirements to use JDK 1.4 or higher. ■ Description: httpclient extension and enhances the standard java.net package, is a wide range of code libraries, which is extremely rich, and can construct a variety of distributed applications that use HTTP protocols, or embedded to existing applications. Increase the ability to access the HTTP protocol. In the Commons Stabilization, the HTTPClient documentation seems to be more perfect than other packages, and there are several examples. Below

Through a simple example, you can learn how to extract a web page, there is a similar example in the HTTPClient document, and we will expand that example to support SSL. Note This example requires JDK 1.4 support because it uses the Java Secure Socket Connection library, and this library is only available in JDK 1.4 and higher. 1 First determine a page that can be downloaded by HTTPS, this example is https://www.paypal.com/. Make sure that the% java_home% / jre / lib / security / java.security file contains the following line code: security.provider.2 = com.sun.net.ssl.internal.ssl.Provider. In addition to these settings, the HTTPS connection has no other particular place - at least for this example. However, if the root certificate used by the remote website is not recognized by the Java you use, you must first import its certificate. 2 Create an instance of HTTPClient. The HTTPCLIENT class can be seen as the main drive of the application, and all the functions of the network relies on it. The HttpClient class requires a Connection Manager to manage connections. HTTPConnectionManager allows us to create its own connection manager, or we can also use built-in SimpleHttpConnectionManager or MultithreadedhttpConnectionManager class. If you do not specify a connection manager when you create HTTPCLIENT, HttpClient uses SimplehttpConnectionManager by default. // Create an instance of httpclient httpclient client = new httpclient (); 3 Create an instance of httpMethod, which is determined which transmission method for communication with the remote server, HTTP allows the transmission methods including: GET, POST, PUT, Delete, Head, Options, and Trace. These transmission methods are implemented as an independent class, but all of these classes implements HTTPMETHOD interfaces. In this example, we use GetMethod, create getMeth

The OD instance specifies the URL we want to get in the parameter. // Create an instance of httpMethod httpmethod method = new getMethod (URL); 4 Execute the extraction operation defined by the HTTPMETHOD. After the execution is completed, the ExecuteMethod method will return the status code of the remote server report. Note that ExecuteMethod is httpclient instead of httpmethod. // Execute the extraction operation of HttpMethod definition statuscode = client.executeMethod (Method); 5 Read the response returned by the server. If the previous connection operation fails, the program will encounter HTTPEXCEPTION or IOException, where IOException generally means that the network is wrong, and continues to try is not likely to succeed. The response returned by the server can be read according to a variety of ways, such as an array, as an input stream, or as a string. After getting the response returned by the server, we can dispose of it according to your needs. Byte [] responsebody = method.getResponsebody (); 6 The last thing to do is to release the connection. Method.releaseConnection (); The above is only very simple to introduce the HTTPClient library. The actual functionality of httpclient is much more rich than this article, not only robust and efficient, please refer to the API documentation for details. 3.3 Net ■ Overview: A underlying API for operating the Internet underlying protocol. ■ Official resources: home page, binary, source code. ■ When applies: When you want to access a variety of Internet underground protocols (Finger, WHOIS, TFTP, Telnet, POP3, FTP, NNTP

, And SMTP). ■ Sample application: NetDemo.java. The ClassPath is required to include Commons-Net-1.0.0.jar. ■ Description: The NET package is a powerful, professional class library, and the class in the class library is originally a commercial product called NetComponents. The NET package not only supports access to a variety of low-level protocols, but also provides a high-level abstraction. In most cases, the abstraction provided by the NET package can meet the general needs, which makes developers no longer need to directly face the low-level commands of the Socket level of the various protocols. Using high-level abstraction does not reduce any feature, NET API is well done in this regard, providing adequate features, not too much compromise in feature. SocketClient is a fundamental class that supports all protocols, which is an abstract class that aggregates public functions required by various protocols. The use of various agreements is actually very similar. First, use the Connect method to establish a connection to the remote server, perform the necessary operation, and finally terminate the connection with the server. The specific use steps are described below by example. // ... // 1 Create a client. We will use nntpclient // to download newsgroups from the news server. Client = new nntpclient (); // ... // 2 Connect to the news server with the client created. // This is a small server that is a small newsgroup. Client.connect ("Aurelia.deine.Net"); // ... // 3 Extract the list of newsgroups. The following command will return an array of // newsGroupInfo objects. If you do not include a newsgroup on the specified suit // manager, the returned array will be empty, // If an error is encountered, the return value is NULL. List = client.listnewsgroups (); //...// 4 Finally terminate the connection to the server. if (client.isconnected ()) client.disconnect (); must be explained, the listnewsgroups command may take a long time to return, on the one hand because the network speed is affected, it may be due to the list of newsgroups huge. The newsgroupinfo object contains detailed information about the newsgroup and provides a command of the operation newsgroup, such as extracting the total number of articles, the last published article, the permission to publish the article. Other clients, such as fingerclient, pop3client, telnetClient, etc., usage is similar. Conclusion: The introduction to the web-related class and other classes is over. In the next article, we will explore the XML classes and packaging classes, and the last article describes the tool class. I hope the reader is interested in trying the program example provided in this paper. Many times Jakarta Commons give people a feeling of confusion, I hope this article has deepened you to learn from Jakarta Commons, or at least in your interest in the Commons sub-project and it provides the various practical APIs and libraries.

The second part XML class and packaging class last article, we divide the components of Jakarta Commons into five categories, introduced the Web classes and other classes. This article introduces the XML class and packaging classes, the next last one An article will introduce the tool class. Note that Commons itself does not perform this classification, and it is purely for organization convenience. 1. Packaging class This category contains two components of CODEC and MODELER. 1.1 CODEC ■ Overview: Provides commonly used encoders and decoders. ■ Official resources: home page, binary, source code. ■ When applies: When you need the standard implementation of the Base64 and HEX encoding functions. ■ Example Application: CodecDemo.java. The ClassPath must contain commons-codec-1.1.jar. ■ Description: The class in CODEC is divided into two packages, one of which is implemented for common Base64 and HEX encoding mechanisms, and the other package is a language, voice coding. The usage of the two packages is similar, in view of the language, voice coding is not very common, so the first package is mainly introduced. Base64 encoding is mainly used for Email transmission. Defining the RFC of the MIME document to specify the base 64 encoding, so that any binary data can be converted to a printable ASCII character set is securely transmitted. For example, suppose you want to transfer a graphic file via email, the Email client software will use the base64 encoding to convert the binary data of the graphic file to the ASCII code. In the base64 encoding, each 8-bit byte is encoded into a group of 4 characters, each character contains 6 digits in the original 24 bits, and the encoded string size

It was 1.3 times the original, and the "=" symbol at the end of the file. In addition to the MIME document, Base64 encoding technology is also used in the "User: Password" string of the HTTP certification head in the Basic authentication mechanism. Base64 class is quite simple, the main two static methods are: base64.encodebase64 (byte [] ByteArray), execute Base64 encoding in the content specified in the byte array; base64.Decodebase64 (byte [] byterray), Used to perform Base64 decoding in the content specified in the byte array. In addition, Base64 also has a static method base64.isArrayBytebase64 (Byte [] ByteArray), which is used to detect whether the specified byte array can be tested through the base64 (ie, data encoded through the base64, as mentioned, Base64 encoded) The result contains only the printable ASCII characters). byte [] encodedBytes = Base64.encodeBase64 (testString.getBytes ()); String decodedString = new String (Base64.decodeBase64 (encodedBytes)); System.err.println ( "/ '^ /' is a valid Base64 characters? " Base64.isArrayBytebase64 (InvalidBytes)); HEX encoding / decoding is the conversion between performing byte data and equivalent hexadecimal representation. The HEX encoded encoding, the decoding process, and the base64 are similar, and details are not described here. 1.2 Modeler ■ Overview: According to the definition of the JMX (Java Management Extensions specification, support configuration and instantiation of Model MBean (Managed Bean) is supported. ■ Official resources: home page, binary, source code. ■ When applies: When you want to create and manage Model MBean to manage applications with standard management APIs. ■ Sample application: ModelerDemo.java, DemomanagedBean.java and MBeans-Descriptors.xml. ClassPath is required to include Commons-Modeler-1.0.jar, Commons-Logging.jar, Commons-Digester.jar, Commons-Collections.jar, and SUN JMX Reference Implement JMXri.jar. ■ Description: The following description requires readers to have a certain understanding of JMX. The Managed Bean is referred to as MBean, is a bean associated with the managed components in the application is an abstraction of resources. ModelMbean is a special MBean with high dynamic and configurable features, but this ability of Model MBean is cost, programmers need to set a large amount of meta information to tell JMX how to create Model MBean, which includes components Attributes, operations, and other information. The purpose of Modeler is to reduce the workload of programmers to implement Model MBean, which is convenient for processing metadata information. In addition, Modeler also provides a registration tool and a basic Model MBean. Modeler allows metadata information to be defined in the form of an XML file, which should comply with the DTD definition provided with Modeler.

Metadata information is used to create registration information at runtime, and the registration information is the central knowledge base of all Model MBeans, which is actually equivalent to a factory that creates such beans. Below we first create this XML file for a Managed Bean. DemomanageDbean has a name property that is readily read. can be seen, this XML file provides many ManagedBean Information, including its properties, constructor, and its operation (but this example is not displayed), this is the so-called metadata information. If you plan to extend the standard MBean (called Basemodelmbean) provided with Modeler, you can specify the class name of Model MBean in the MBEAN element:. In the previous example, the standard Model MBean simply passes all calls directly to the ManageDbean class. Next, we have to register the above information. Note After the file is loaded with the registration information, we extract formatted registration information through a static method: // Create a registryregistry registry = null; try {url url = modelerdemo.class.getResource ("mbeans-descriptors.xml) ; InputStream stream = url.openStream (); Registry.loadRegistry (stream); stream.close (); registry = Registry.getRegistry ();} catch (Throwable t) {t.printStackTrace (System.out); System.exit (1);} After Creating the registry, we have to create a Model MBean and register it to the default management server. In this way, any JMX client can call the Managed Bean through Model MBean.

// get a Managed Bean instance handle DemoManagedBean mBean = new DemoManagedBean (); // create a Model MBean, and it is registered in the MBean server MBeanServer mServer = registry.getServer (); ManagedBean managed = registry.findManagedBean ( "ManagedBean" ); try {ModelMBean modelMBean = managed.createMBean (mBean); String domain = mServer.getDefaultDomain (); ObjectName oName = new (domain ObjectName ": type = ManagedBean"); mServer.registerMBean (modelMBean, oName);} catch (Exception e) {System.err.println (e); System.exit (0);} try {ObjectName name = new ObjectName (mServer.getDefaultDomain () ": type = ManagedBean"); ModelMBeanInfo info = (ModelMBeanInfo) Mserver.getmbeanInfo (Name); System.err.Println ("classname =" info.getClassName ()); System.err.Println ("Description =" info.getdescription ()); system.rr.println (" MBeandescriptor = " info.getmbeadescriptor ()); system.rr.println (" ==== Test ==== "); System.err.Println (" Name of the original value: " mServer.GetaTribute (name, "name")); mserver.setttribute (Name, New Attribute ("Name", "Vikram"); ​​System.err.Println ("Name new value:" m Server.getaTribute (name, "name"));} catch (exception e) {system.err.println (e); system.exit (0);} Although this example is relatively simple, it still clearly illustrates the use Modeler brings easy to compare it to create a similar Model MBean without using Modeler. Description ModelMbeanInfo is not only flexible, but also is also easy to expand, but also to scale this type of information than manually. Second, the XML class XML class contains classes related to Java, XML technology, including: BetWixt, Digester, Jelly, and JXPath. 2.1 BetWixt ■ Overview: Implement the map of XML and JavaBean. ■ Official resources: home page, binary, source code. ■ When you apply: When you want to implement XML and beans mappings in a flexible manner, you need a data binding framework.

■ Sample application: Betwixtdemo.java, Mortgage.java, Mortgage.xml. It is required to include Commons-Betwixt-1.0-alpha-1.jar, commons-beanutils.jar, commons-colors.jar, and commons-colorster.jar must be included in CLASSPATH. ■ Description: If you have used the Castor binding data, you will be able to enjoy the flexibility of BetWixt. CASTOR is suitable for executing the conversion between beans and XML on a predefined mode (Schema); but if you only want to perform data and XML conversion, the best choice is Betwixt. Betwixt features flexible, convenient to output data to human readable XML. The usage of BetWixt is quite simple. If you want to convert the bean into XML, first create an instance of BeanWriter, set its properties, then output; if you want to convert XML to bean, first create an instance of BeanReader, set its properties, and perform conversion with Digester. Convert Bean into XML: // convert the bean into XML instances with BETWIXT to XML must have instances of BeanWriter. / / Since BeanWriter's constructor has a writer object, // So we start StringWriter outputWriter = new stringWriter () from creating a StringWriter (); // Note that the output is not formatted, so you need to start //// Write the following: OutputWriter.write ("

Beanreader Reader = new beanreader (); // Register Try {reader.registerBeanClass (Mortgage.class); // and parsing it ... Mortgage MortgageConvered = (Mortgage) Reader.Parse (New File)); // Check if the converted MortGage contains the value in the file system.err.println ("Rate:" MortGageConverted.Getrate () ", YEARS:" MortGageConverted.GetyEars ());} catch (Exception EE) { Ee.PrintStackTrace (); Note, when you register with the BeanReader, if the name of the top element is different, you must register and specify an accurate path with another method, such as Reader.RegisterBeanclass ("TopLelelementName", Mortgage.class ). 2.2 Digester ■ Overview: Provides a friendly, event-driven advanced XML document processing API. ■ Official resources: home page, binary, source code. ■ When you apply: When you want to process an XML document, and you want to perform some operations based on a set of rules triggered in the XML document. ■ Sample application: DigesterDemo.java, Employe.java, Company.java, Rules.xml, and Company.xml. ClassPath must be included in Commons-Digester.jar, Commons-Logging.jar, Commons-BeanuTils.jar, and Commons-Collections.jar. ■ Description: Digester is the most useful when parsing the configuration file. In fact, Digester is initially developed for reading the Struts profile, and then moved to the CommONS package. Digester is a powerful mode matching tool that allows developers to process XML documents at a higher level than SAX or DOM APIs, which can trigger a set of rules when they find specific patterns (or find modes). Basic ideas using Digester are: First create an instance of Digester, then use it to register a range of modes and rules, and finally pass the XML document to it. Thereafter, Digester will analyze the XML document, trigger rules according to the registration order. If an element in the XML document matches one or more rules, all rules will be triggered in order according to the order of registration. Digester itself has 12 predefined rules. When you find a specific mode in the XML document, do you want to call a method? Very simple, use predefined CallMethodRule! In addition, you don't have to use a predetermined rule, Digester allows users to define their own rules by extending the Rule class. When specified mode, the element must be given by absolute name. For example, the root element is specified directly with the name, and the next layer element is drawn from the "/" symbol. For example, suppose companies are root elements, and Company / Employee is a mode that matches one of the child elements. Digester allows wildcards, such as * / Employee, will match all EMPLOYEEEE elements that appear in the XML document.

When you find a match mode, there are four callback methods that are associated with the matching mode, they are: begin, end, body, and finish. These methods are called by the time as indicated by their name, such as when the time to call Begin and End is when the start tag and end tag are encountered. It is called after the processing of the matching mode is completed. Finally, the mode can be specified in an external rule XML document (using digester-rules.dtd), or specified within the code, the following is the first approach, because this method is more common. Create two XML documents before using Digester. The first is a data or configuration file, that is, we prepare a file for its application rules. Here is an example (company.xml) My company

China Zhejiang < Name> Sun Wukong 10000 Pig Eight Rings second file It is the rule file rules.xml.

Rules.xml tells Digester to find what to find in Company.xml, what operations do after finding: What implications have this file? The first rule, tells Digester If you encounter a mode companies, you must follow the object-create-rule, that is, create a class instance! So what kind of instance is it to create? The className = "Company" property specifies the name of the class. Therefore, when analyzing Company.xml, when you encounter a top company element, wait until the Object-Create-Rule rule is executed, we have an instance of a COMPANY class created by Digester. Now you have to understand that the call-method-rule rules should not be so difficult. The function of call-method-rule is to call a method (the name of the method via the methodname property) when encountered in Company / Name or Company / AddRESS mode (specified by the methodname property). The last pattern match is worth noting that it is nested in the matching mode. The way two setting rules and patterns are Digester Accepted, and we can choose anything according to your needs. In this example, the rules defined in the mode create an object of the Employee class when encountering the Company / Employee mode, sets its properties, and finally uses set-next-rule to add this employee to the top layer.

After creating the two XML files above, you can call Digester using two lines of code: Digester Digester = DigesterLoader.createdIgester (rules.tourl ()); Company company = (company) Digester.Parse (InputXMLFile); first line The code is loaded into the rule file, create a Digester. The second line of code uses the Digester to apply the rules. See DigesterDemo.java provided later in this article. 2.3 Jelly ■ Overview: A scripting language based on Java and XML. ■ Official resources: home page, binary, source code. ■ When applies: Simply say, when you want a flexible, scalable XML script tool. ■ Example App: JellyDemo.java, JellyDemo.xml, and TrivialTag.java. It is required to have commons-jelly-1.0-dev.jar, dom4j.jar, commons-logging.jar, commons-beanutils.jar, and commons-collections.jar must be required in ClassPath. ■ Description: To make it clear that Jelly is and it plays it is very difficult. Jelly attempts to provide a universal XML script engine that can be mapped by developers through custom action and tag extensions, and the elements in the XML document are mapped to JavaBean, and the properties of the XML element are mapped to the properties of the JavaBean. In a sense, Jelly is a tool combined with BetWixt and Digester, but Jelly is more powerful and has better scalability. A Jelly system consists of multiple components. The first component is a Jelly script, which is an XML document parsed by Jelly Engine, and the parsed XML document element is bound to jelly tag dynamic processing. The second component is Jelly tag, which is a Javabean that implements Jelly Tag interface. Any Jelly tag can implement a dotag method. This DOTAG method is how the method performed when the scripting is encountered in the XML document. . Jelly is a dynamic script processing capability through this mechanism. From a sense, it is a bit similar to Digester's working mechanism. Jelly has many predefined tags, some of which provide core Jelly support, other tags are used to provide support for resolution, loop, condition execution code. In addition, Jelly also provides a wide range of support for Ant tasks. To use Jelly in a Java application, first create an example of JellyContext, for example: JellyContext context = new jellyContext () ;. We can see JellyContext objects as a running environment compiling and run Jelly scripts. With JellyContext, you can run Jelly scripts. The output of JellyContext is actually an instance of an XMLOUTPUT class: Context.Runscript (New File ("JellyDemo.xml"), Output) ;.

When you create a custom tag, we can overwrite the DOTAG methods mentioned above (as shown in the following example), or provide an execution method, such as invoke () or run (): public void dotag (xmloutput output) throws Exception { / / Add to the action to be executed, //, for example, set an attribute, access the file system, etc. ... this.intprop = 3;} The following provides an XML file example of the Jelly script: Hello World This example is used to jelly: define and Jelly: Core tag, and a TrivialTag tag. When encountering a TRIVIAL tag instance, Jelly creates an instance of the corresponding JavaBean, execute the DOTAG method (or can be a RUN or INVOKE.). Jelly has many other features that can be run directly from the command line or Ant script, or within the code of the application, see the Jelly documentation for details. 2.4 JXPATH ■ Overview: XPath Interpreter in Java. ■ Official resources: home page, binary, source code. ■ When applies: When you want to apply XPath queries in the structure composed of JavaBean, DOM, or other objects. ■ Sample application: jxpathdemo.java, book.java, author.java. The ClassPath must contain common-jxpath-1.1.jar. ■ Description: The following description requires readers already have basic XPath knowledge. XPath is a language that queries an XML document. JXPath applies the same concept to other Java object queries, such as JavaBean, Collection, Array, and Map. JXPathContext is the core class in JXPath, which uses a factory method to locate and create an instance of a context. Because of this mechanism, the developer can insert a new JXPath implementation when necessary. To use JXPathContext, just simply pass a JavaBean, Collection or Map, for example: jxpathcontext context = jxpathcontext.newcontext (book) ;. Many tasks can be implemented using JXPathContext.

For example, access attributes or nested properties, of course, attributes can also be set: System.err.Println ("Title"); system.rr.println ("Author / AuthorID"); context. SetValue ("Author / AuthorId", "1001"); use JXPath to find other types of objects, but the way to create a context object is the same, it is a new context with the static method described above, it is incompatible The object of query. Conclusion: The introduction of the package and XML classes is over here. In the next article, we will learn about the tool class. In the first article of this series, we divide the components contained in the Commons project into five categories, introduced the web class and other classes. The second article Theory and XML class and packaging classes. This is the last one to explore the components of the tool class. Note that Commons itself does not perform this classification, and the classification is purely description and organization convenience. Part III, tool class tools contain several components of BeanUtils, Logging, DBCP, Pool, and Validator. I. Beanutils ■ Overview: Tools for dynamic operation JavaBean. ■ Official resources: home page, binary, source code. ■ When applies: When you need to dynamically access JavaBean, you don't know what to compile. Accessor and Modifier. The dynamically accessed JavaBean must follow the naming design specification defined by JavaBeansSpecification. ■ Sample application: beanutilsdemo.java, applayer1bean.java, applayer2bean.java, subbean.java. The CLASSPATH must be included in COMMONS-beanUtils.jar, Commons-Logging.jar, and Commons-Collectes.jar. ■ Description: In a dynamic Java application design environment, we do not necessarily understand the various sets, GET methods of JavaBean. Even if the name of these methods is already known, write the setxxx or getxxx method for each attribute of Bean. Consider this situation: Several almost identical beans are passed from a layer of the application to another layer, will you call bean1.setxxx (bean2.getxxx ()) for each property? Although you can do this, it is not always doing this, because you can let Beanutils complete these cumbersome operations! Beanutils can help developers dynamically create, modify, and copy JavaBeans. BeanUtils can operate JavaBean: (1) of the following conditions: JavaBean must provide a constructor without parameters. (2) JavaBean's properties must be able to access and modify through Getxxx and Setxxx methods. ISXXX and SETXXX are also allowed for Boolean properties. JavaBean's properties can be read-only or only written, that is, allow only SET or GET methods for properties. (3) If there is no traditional naming mode (ie, use GET and SET), change other ways to name JavaBean Accessor and Modifier

Then, this must be declared by the BeanInfo class associated with JavaBean. Let's take a simple example. To get the simple properties of JavaBean, use PropertyUtils.getsImpleProperty (Object Bean, String Name), and PropertyUtils.SetSimpleProperty (Object Bean, String Name, Object Value). As shown in the example below, the applayer1bean.java and applayer2bean.java define two JavaBeans for two tests. PropertyUtils.setSimpleProperty (app1Bean, "intProp1", new Integer (10)); System.err.println ( "App1LayerBean, stringProp1:" PropertyUtils.getSimpleProperty (app1Bean, "stringProp1")); Since we can call directly Bean Method (App1Bean.getStringProp1 () or app1bean.setintprop1 (10)) to get the properties of the bean, why should I use SetsImpleProperty, GetSimpleProperty? This is because we don't necessarily know the name of the JavaBean property, so it is not necessarily known which methods to call to get / set the corresponding properties. The names of these attributes may come from other processs or external applications. Therefore, once the name of the JavaBean's attribute is made and saved it to a variable, you can pass the variable to PropertyUtils, no need to rely on other developers to pre-know the correct method name. So, if the attribute of JavaBean is not a simple data type, what should I do? For example, the attribute of JavaBean may be a collection or a MAP. In this case, we have to change PropertyUtils.GetIndexedProperty or PropertyUtils.getMappedProperty. For the collection class attribute value, we must specify an index value, specify the value of the value to be extracted or set in the collection; for the MAP class attribute, we must specify a key to indicate which value to extract. Below is two examples

Sub: PropertyUtils.setIndexedProperty (app1Bean, "listProp1 [1]", "new string 1"); System.err.println ( "App1LayerBean, listProp1 [1]:" PropertyUtils.getIndexedProperty (app1Bean, "listProp1 [1] ")); Please note that for indexed properties, the index value is passed through square brackets. For example, in the above example, we set the value of the index of javabean (app1bean) to a "new string 1", which takes the same value from the location of the index 1. There may be another way to achieve the same objective, namely the use of PropertyUtils.setIndexedProperty (Objectbean, String name, int index, Object value) and PropertyUtils.getIndexedProperty (Object bean, String name, int index) method, the two Method Since the index value is passed as a method of parameter. For MAP class properties, there are similar methods, as long as the key (rather than index) is changed, or set the specified value. Finally, the property of the bean may be a bean. So how do you get or set those properties beans from the primary bean? Just use PropertyUtils.getnestedProperty (Object Bean, String Name) and Property (Object Bean, String Name, Object Value) method. An example is provided below. // set access and nested properties PropertyUtils.setNestedProperty (app1Bean, "subBean.stringProp", "information from SubBean through setNestedProperty settings."); System.err.println (PropertyUtils.getNestedProperty (app1Bean, "subBean.stringProp ")); It can be seen from the example above that the attribute of the dependent bean is accessed by a period symbol. The above ways described above can be used together, and the nesting depth is not limited. The two methods to be used are PropertyUtils.getProperty (Object Bean, String Name) and PropertyUtils.SetProperty (Object Bean, String Name, Object Value). For example: PropertyUtils.SetProperty (App1bean, "Subbean.listProp [0]", "Value of the Attribute") ;. This example is to access the nested bean objects and the canotic properties. BeanUTILS is often used to dynamically access request parameters in web applications. In fact, it is the inspiration of beanutils to trigger the Struts project to dynamically convert the request parameters into system javabean: Use the code to convert the user fill in the form into a map, where the name of the parameter becomes the key in the map, from the value of the parameters The data entered in the form is entered in the form, then converting these values ​​into a system bean by a simple beanutils.populate call.

Finally, Beanutils provides a step from a step to another bean from a bean to another bean: // copies the data of App1Bean to App2BeanBeanutils.copyProperties (App2bean, App1bean); BeanUtils also has some practical methods that have not been mentioned here. But don't worry, beanutils is one of the comprehensive components of documentation in Commons. It is recommended that the reader will read the relevant information of the remaining methods for the Javadoc documentation of the BeanUtils package. Second, Logging ■ Overview: A codebook that encapsulates many popular log tools and provides a unified log access interface. ■ Official resources: home page, binary, source code. ■ When applies: When your application requires more than one log tool, or when it is expected to have this requirement. ■ Example Application: LoggingDemo.java, Commons-logging.properties. It is required to include commons-logging.jar in ClassPath, sometimes log4j.jar. ■ Description: Logging enables us to debug and track the behavior and status of any time at any time. In any larger application, Logging is an integral part, so there are many third-party logging tools, which exempt from developers to write the Logging API. In fact, even if JDK has a structured Logging API. Since there are so many options (log4j

, JDK, Logkit, etc.), usually we can always find the ready-made API that is best suited for your application. However, there may be an exceptional situation, such as a familiar Logging API that cannot be compatible with the current application, or because of some kind of hard regulations, or due to the application of the architecture. The case of the Commons project Logging component is to package the functionality of the log log into a set of standard APIs, but its underlying implementation can be arbitrarily modified and transformed. Developers use this API to perform commands of log information, by the API to deliver these commands to the appropriate underlying handle. Therefore, for developers, the Logging component is neutralized for any specific underlying implementation. If you are familiar with Log4j, you should not have any problems with the logging API using your COMMONS. Even if you are not familiar with log4j, just know that you must import two classes using Logging, create a log's static instance, the following shows the code: import org.apache.commons.logging.log; import org.apache.commons. Logging.logfactory; public class loggingdemo {private static log log = logfactory.getlog (loggingdeMo.class); // ...} It is necessary to explain what happened when the logFactory.getlog (). Calling this function will start a discovery process, that is, identify the implementation of the required underlying logging function, and the specific discovery process is listed below. Note that no matter how the underlying log tool is found, it must be a class that implements the log interface, and must be in the classpath. Commons Loggingapi directly provides support for the following underlying logging tools: JDK14Logger, Log4jlogger, LogkitLogger, Nooplogger (directly discarding all log information), as well as a SimpleLog. (1) Commons Logging first looks for a commons-logging.properties file in ClassPath. This attribute file must define the org.apache.commons.logging.log property, which should be the full qualified name implemented by any of the above log interfaces. (2) If the above step fails, Commons's logging then checks the system properties org.apache.commons.logging.log. (3) If you can't find the org.apache.commons.logging.log system properties, Logging then looks for the Log4J class in ClassPath. If found, Logging assumes that the application is log4j. However, the property of the log4j itself is still configured by log4j.properties file. ⑷ If the above lookups cannot find the appropriate logging API, but the application is running on JRE 1.4 or later, the JRE 1.4 logging feature is used by default. ⑸ Finally, if the above operation fails, the application will use the built-in SimpleLog. Simplelog outputs all log information directly to System.err. After obtaining an appropriate underlying logging tool, you can start the log information. As a standard API, the main benefit of the Commonslogging API is to establish an abstract layer on the basis of the underlying log mechanism, convert the call to the log record command associated with the specific implementation by the abstraction layer. The sample program provided herein will output a prompt message telling you which underlying log tool is currently using.

Try running this program in different environmental configurations, for example, running this program without specifying any properties, then JDK14Logger will be used by default; then specify system properties-Jorg.Apache.commons.logging.log = Org .apache.commons.logging.Impl.SIMPLOG Runner, then the logging tool will be simplelog; finally, put the log4j class into the classpath, just set the log4j log4j.properties configuration file, you can get the log4jlogger output Information

. Third, POOL ■ Overview: The code library used to manage the object pool. ■ Official resources: home page, binary, source code. ■ When applies: When you need to manage an object instance pool. ■ Sample application: Poolomo.java and MyObjectFactory.java. There must be commons-pool.jar and commons-collections.jar in ClassPath. ■ Description: The pool component defines a set of interfaces for the object pool, and also provides several universal object pool implementations, as well as some fundamental classes that help developers create objects. For most developers, the object pool should not be a new concept. Perhaps many readers have used the database connection pool when accessing the database, and the concept of the object pool is actually similar. The object pool allows developers to create a set of objects in the buffer (create an object's operation can be done by the application's configuration file, or can be completed at the startup phase of the application), can be obtained quickly when the application needs to be used Respond. If the application no longer needs an object, it still returns an object to the buffer pool, and then extract from the buffer pool when you need to use the object next time. The pool component allows us to create an object (instance) pool, but do not limit we must use a specific implementation. The pool component itself provides several implementations, and we can also create your own implementation if necessary. The pool component contains three basic classes: ObjectPool, this is an interface for defining and maintaining the object pool; ObjectPoolFactory, is responsible for creating an instance of ObjectPool; there is a PoolableObjectFacotry, which defines a group of lives for the instances used within ObjectPool Cycle method. As indicated earlier, the Pool component contains several general implementations, one of which is genericObjectPool, below to see its usage by one instance. 1 Create a pooLableObjectFactory. This factory class definition object is created, dismantled, and verified. import org.apache.commons.pool.PoolableObjectFactory; public class MyObjectFactory implementsPoolableObjectFactory {private static int counter; // return a new string public Object makeObject () {return String.valueOf (counter );} public void destroyObject (Object obj ) {} public boolean validateObject (object obj) {return true;} public void activateObject (object obj) {} public void passivateObject (object obj) {}} this example creates a pool number increasing String object, verification operation (ValidateObject) always returns True. 2 Create a genericObjectPool, MaxActive, MaxIdle and other options using PoolableObjectFactory. GenericObjectPool Pool = New genericObjectPool (New MyObjectFactory ()); 3 from the object pool "Borrow" an object. System.err.println ("Borrowed:" pool.borrowObject ()); 4 returns the object to the object pool.

Pool.ReturnObject ("0"); the status of the object pool can be known in various ways, for example: // How many objects have been activated (borrowed)? System.err.Println ("The number of objects of the current activity:" pool.getnumactive ()); PoolDemo.java provided later later provides a complete source code. Fourth, DBCP ■ Overview: Database connection pool. Based on the POOL component. ■ Official resources: home page, binary, source code. ■ When applies: When you need to access the relational database. ■ Sample application: dbcpdemo.java. Requires CLASSPATH must have commons-dbcp.jar, commons-pool.jar, and commons-collections.jar. Also be able to access the database, configure the JDBC driver suitable for the database. The sample application is tested is a MySQL database connection, and the driver is MySQL JDBCDRIVER. Note that running this program requires the Nightly version of the binary file, and the current formal distribution lacks some essential classes. Finally, when running this sample program, be sure to be JDBC

The driver sets the system properties (-djdbc.drivers = com.mysql.jdbc.driver). ■ Description: On the basis of the POOL component, DBCP provides a database connection buffer pool mechanism. Compared to conventional connection pools, DBCP is a bit more complicated because its idea provides a universal system in the form of a pseudo JDBC driver. However, we have learned the basic knowledge of the Pool component, and now I understand that DBCP usage should be very simple. // ... // 1 Create an instance of a GenericObjectPool class. GenericObjectPool pool = new genericObjectPool (null); // ... // 2 When you discuss the pool component, genericObjectPool // requires that there is a PoolableObjectFactory to create an instance of Object to // to buffer, for DBCP, / / // provide this function is now supplied by PoolableConnectionFactory, as shown in the following example: DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory ( "jdbc: mysql: // host / db", "username", "password"); PoolableConnectionFactory pcf = new PoolableConnectionFactory (CF, Pool, NULL, "Select * from mysql.db", false, true); // ... // 3 Now we just create and register PoolingDriver: new poolingdriver (). Registerpool ("mypool", Pool); Next, you can extract from this connection pool. Note that the default value of MaxActive, MaxIdle and other options when creating this connection pool, if necessary, you can customize these values ​​when you create an instance of the GenericObjectPool class in front step 1. DBCPDemo.java provides a complete instance. V. Validator ■ Overview: A API that collects common user input verification functions. ■ Official resources: home page, binary, source code. ■ When applies: When JavaBean performs a regular verification operation. ■ Example App: ValidatorDemo.java, MyValidator.java, MyFORMBEAN.JAVA, VALIDATION.XML. Requires ClassPath must have commons-validator.jar, commons-beanutils.jar, commons-collections.jar, common-digester.jar, and commons-logging.jar. ■ Description: If you have developed a web application with Struts, you should have used the Validator package. The Validator package is extremely simple to simplify the user input data. However, Validator is not limited to web applications, which can also be easily used in other applications that use JavaBean. Validator allows the user input domain to define validation conditions, support error information internationalization, allowing a custom verifier, and the Validator package also provides some predefined validiarons.

Verify rules and verification methods are defined with an XML file (you can define one or more XML files, but usually, it is well separated). The verification method file defines the validator to be used, specifying the Java classes that actually implement the validator (not required to implement certain specific interfaces, nor require these classes to be derived from specific classes, only need to define the method The definition of the declaration in the file is OK). Let's construct a custom verifier, its function is to check if a String property of the bean contains a specific character ("*"). import org.apache.commons.validator *;. public class MyValidator {public static boolean validateContainsChar (Object bean, Field field) {// get first Bean properties (i.e., a String) String val = ValidatorUtil.getValueAsString (bean, field .getProperty ()); // Returns TRUE or FALSE based on whether or not "*" characters in the properties. Return ((Val.IndexOf ('*') == -1)? false: true);}} The ValidatorUtil class provides many utility, such as ValidatorUtil.getValueAsstring to extract the property value of the bean and return a string. Now we have to declare the MyValidator verifier in the XML file. It can be seen that the XML file details the feature of the verification method, including the input parameters of the method. Let's take a look at the steps using this verifier. 1 Join the verification rules we want to implement in the XML file above. It can be seen that all verification rules declare within the Formset element. Formset elements are first declare that the form to verify, and the input domains to verify are listed within the form and their verification conditions. In this example, we want to verify the MyFormBean's Name property, check whether the attribute is able to verify through the ContainsStar (that is, whether the value of the Name property contains "*" characters). 2 Based on the XML file, create a validator instance and initialize.

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

New Post(0)