Address: http://blog.csdn.net/ocelight/archive/2009/09/02/4510192.aspx
Http://commons.apache.org/
Apache commons contains many open-source tools to solve common programming problems and reduce repetitive work. I have selected some common projects for a brief introduction. I used a lot of online ready-made items in this article. I just made a summary.
Commons beanutils
Http://jakarta.apache.org/commons/beanutils/index.html
Description: A bean tool set. Beanutils also performs some packaging on the basis of a bunch of get and set beans.
Examples: There are many features and detailed descriptions on the website. A common function is bean copy, which is the property of copy bean. It will be used for hierarchical architecture development, such as copying data from Po (Persistent Object) to VO (value object ).
The traditional method is as follows:
// Obtain the teacherform
Teacherform = (teacherform) form;
// Construct a teacher object
Teacher = new teacher ();
// Assign a value
Teacher. setname (teacherform. getname ());
Teacher. setage (teacherform. getage ());
Teacher. setgender (teacherform. getgender ());
Teacher. setmajor (teacherform. getmajor ());
Teacher. setdepartment (teacherform. getdepartment ());
// Persists the teacher object to the database
Hibernatedao =;
Hibernatedao. Save (teacher );
After using beanutils, the code is greatly improved, as shown below:
// Obtain the teacherform
Teacherform = (teacherform) form;
// Construct a teacher object
Teacher = new teacher ();
// Assign a value
Beanutils. copyproperties (teacher, teacherform );
// Persists the teacher object to the database
Hibernatedao =;
Hibernatedao. Save (teacher );
Commons CLI
Http://jakarta.apache.org/commons/cli/index.html
Note: This is a tool for processing commands. For example, the string [] entered by the main method needs to be parsed. You can pre-define the parameter rules and then call CLI for parsing.
Example:
// Create options object
Options = new options ();
// Add t option, option is the command parameter, false indicates that
// This parameter is not required.
Options. addoption ("T", false, "display current time ");
Options. addoption ("C", true, "Country Code ");
Commandlineparser parser = new posixparser ();
CommandLine cmd = parser. parse (options, argS );
If (CMD. hasoption ("T ")){
// Print the date and time
}
Else {
// Print the date
}
// Get C option value
String countrycode = cmd. getoptionvalue ("C ");
If (countrycode = NULL ){
// Print default date
}
Else {
// Print date for country specified by countrycode
}
Commons Codec
Http://jakarta.apache.org/commons/codec/index.html
Note: This tool is used for encoding and decoding, including base64, URL, and soundx. People who use this tool should be clear about this and I will not introduce it much.
Commons collections
Http://jakarta.apache.org/commons/collections/
Note: You can regard this tool as an extension of Java. util.
Example: A simple example
Orderedmap map = new linkedmap ();
Map. Put ("five", "5 ");
Map. Put ("six", "6 ");
Map. Put ("seven", "7 ");
Map. firstkey (); // returns "five"
Map. nextkey ("five"); // returns "six"
Map. nextkey ("six"); // returns "seven"
Commons Configuration
Http://jakarta.apache.org/commons/configuration/
Note: This tool is used to process configuration files and supports many storage methods.
1. properties files
2. XML documents
3. Property list files (. plist)
4. JNDI
5. JDBC datasource
6. System Properties
7. Applet Parameters
8. servlet Parameters
Example: A simple example of Properties
# Usergui. properties, definining the GUI,
Colors. Background = # ffffff
Colors. Foreground = #000080
Window. width = 500
Window. Height = 300
Propertiesconfiguration Config = new propertiesconfiguration ("usergui. properties ");
Config. setproperty ("Colors. Background", "#000000 );
Config. Save ();
Config. Save ("usergui. Backup. properties); // save a copy
Integer integer = config. getinteger ("window. width ");
Commons DBCP
Http://jakarta.apache.org/commons/dbcp/
Note: This is the database connection pool, Tomcat is used. You can go to the website to view the instructions.
Commons dbutils
Http://jakarta.apache.org/commons/dbutils/
Note: When I was writing a database program, I often made a separate package for database operations. Dbutils is such a tool, and you do not need to repeat such work in future development. It is worth noting that this tool is not a popular or-mapping tool (such as Hibernate), but just to simplify database operations, such
Queryrunner run = new queryrunner (datasource );
// Execute the query and get the results back from the Handler
Object [] result = (object []) Run. Query (
"Select * From person where name =? "," John Doe ");
Commons fileupload
Http://jakarta.apache.org/commons/fileupload/
Note: How does the JSP file upload function work?
Example:
// Create a factory for disk-based file items
Fileitemfactory factory = new diskfileitemfactory ();
// Create a new file upload Handler
Servletfileupload upload = new servletfileupload (factory );
// Parse the request
LIST/* fileitem */items = upload. parserequest (request );
// Process the uploaded items
Iterator iter = items. iterator ();
While (ITER. hasnext ()){
Fileitem item = (fileitem) ITER. Next ();
If (item. isformfield ()){
Processformfield (item );
} Else {
Processuploadedfile (item );
}
}
Commons httpclient
Http://jakarta.apache.org/commons/httpclient/
Note: This tool can be used to access the website through programming.
Example: The simplest get operation
Getmethod get = new getmethod ("http://jakarta.apache.org ");
// Execute method and handle any error responses.
...
Inputstream in = Get. getresponsebodyasstream ();
// Process the data from the input stream.
Get. releaseconnection ();
Commons Io
Http://jakarta.apache.org/commons/io/
Note: It can be seen as an extension of Java. Io, which I think is very convenient to use.
Example:
1. Read stream
Standard Code:
Inputstream in = new URL ("http://jakarta.apache.org"). openstream ();
Try {
Inputstreamreader INR = new inputstreamreader (in );
Bufferedreader Buf = new bufferedreader (INR );
String line;
While (line = Buf. Readline ())! = NULL ){
System. Out. println (line );
}
} Finally {
In. Close ();
}
Use ioutils
Inputstream in = new URL ("http://jakarta.apache.org"). openstream ();
Try {
System. Out. println (ioutils. tostring (in ));
} Finally {
Ioutils. closequietly (in );
}
2. Read files
File file = new file ("/commons/IO/Project. properties ");
List lines = fileutils. readlines (file, "UTF-8 ");
3. view the remaining space
Long freespace = filesystemutils. freespace ("C :/");
Commons jxpath
Http://jakarta.apache.org/commons/jxpath/
(XPath) You know, jxpath is an XPATH Based on Java objects, that is, it is used to query Java objects. This is still imaginative.
Example:
Address = (Address) jxpathcontext. newcontext (vendor ).
Getvalue ("locations [Address/zipcode = '000000']/address ");
The above code is equivalent
Address = NULL;
Collection locations = vendor. getlocations ();
Iterator it = locations. iterator ();
While (it. hasnext ()){
Location = (location) it. Next ();
String zipcode = location. getaddress (). getzipcode ();
If (zipcode. Equals ("90210 ")){
Address = location. getaddress ();
Break;
}
}
Commons Lang
Http://jakarta.apache.org/commons/lang/
Note: This Toolkit can be seen as an extension of Java. Lang. Provides tool classes such as stringutils, stringescapeutils, randomstringutils, tokenizer, and wordutils.
Commons Logging
Http://jakarta.apache.org/commons/logging/
Note: Do you know log4j?
Commons math
Http://jakarta.apache.org/commons/math/
Note: You should know what the package is for by name. The features provided by this package are somewhat different from those provided by commons Lang, but this package is more focused on mathematical tools and more powerful.
Commons net
Http://jakarta.apache.org/commons/net/
Note: This package is very practical and encapsulates many network protocols.
1. FTP
2. nntp
3. SMTP
4. POP3
5. Telnet
6. TFTP
7. Finger
8. Whois
9. rexec/RCMD/Rlogin
10. Time (rdate) and daytime
11. Echo
12. Discard
13. NTP/SNTP
Example:
Telnetclient Telnet = new telnetclient ();
Telnet. Connect ("192.168.1.99", 23 );
Inputstream in = Telnet. getinputstream ();
Printstream out = new printstream (Telnet. getoutputstream ());
...
Telnet. Close ();
Commons validator
Http://jakarta.apache.org/commons/validator/
Note: This tool is used for verification. For example, verify whether the email string and date string are valid.
Example:
// Get the date validator
Datevalidator validator = datevalidator. getinstance ();
// Validate/convert the date
Date foodate = validator. Validate (foostring, "DD/MM/YYYY ");
If (foodate = NULL ){
// Error... not a valid date
Return;
}
Commons Virtual File System
Http://jakarta.apache.org/commons/vfs/
Description: Provides access interfaces for various resources. Supported resource types include
1. CIFS
2. FTP
3. Local files
4. HTTP and https
5. SFTP
6. Temporary Files
7. WebDAV
8. Zip, jar and tar (uncompressed, tgz or tbz2)
9. gzip and Bzip2
10. Res
11. Ram
This package is powerful and greatly simplifies the access to resources by programs.
Example:
Read files from jar
// Locate the JAR File
Filesystemmanager fsmanager = VFS. getmanager ();
Fileobject jarfile = fsmanager. resolvefile ("jar: lib/ajarfile. Jar ");
// List the children of the JAR File
Fileobject [] children = jarfile. getchildren ();
System. Out. println ("children of" + jarfile. getname (). geturi ());
For (INT I = 0; I <children. length; I ++)
{
System. Out. println (Children [I]. getname (). getbasename ());
}
Read files from SMB
Staticuserauthenticator auth = new staticuserauthenticator ("username", "password", null );
Filesystemoptions opts = new filesystemoptions ();
Defaultfilesystemconfigbuilder. getinstance (). setuserauthenticator (OPTs, auth );
Fileobject fo = VFS. getmanager (). resolvefile ("SMB: // host/anyshare/DIR", opts );
Some people say that Apache is like a helper, and there are many projects in it. Indeed, Apache project levels are uneven, and different projects often have overlapping functions or even crashes, such as Ant and Maven. However, there are still many outstanding Apache projects, such as Apache HTTP Server, tomcat, ant, And Geronimo. Apache commons is a toolkit that provides support for other projects. Many commons projects are extracted from other projects.