Apache Commons工具集简介

转自:http://zhoualine.iteye.com/blog/1770014

       Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动。下面是我这几年做开发过程中自己用过的工具类做简单介绍。

 

组件功能介绍
BeanUtils提供了对于JavaBean进行各种操作,克隆对象,属性等等.
BetwixtXML与Java对象之间相互转换.
Codec处理常用的编码方法的工具类包 例如DES、SHA1、MD5、Base64等.
Collectionsjava集合框架操作.
Compressjava提供文件打包 压缩类库.
Configuration一个java应用程序的配置管理类库.
DBCP提供数据库连接池服务.
DbUtils提供对jdbc 的操作封装来简化数据查询和记录读取操作.
Emailjava发送邮件 对javamail的封装.
FileUpload提供文件上传功能.
HttpClien提供HTTP客户端与服务器的各种通讯操作. 现在已改成HttpComponents
IOio工具的封装.
LangJava基本对象方法的工具类包 如:StringUtils,ArrayUtils等等.
Logging提供的是一个Java 的日志接口.
Validator提供了客户端和服务器端的数据验证框架.

 

1、BeanUtils 提供了对于JavaBean进行各种操作, 比如对象,属性复制等等。

 

Java代码   收藏代码
  1. //1、 克隆对象  
  2. //  新创建一个普通Java Bean,用来作为被克隆的对象  
  3.   
  4.     public class Person {  
  5.     private String name = "";  
  6.     private String email = "";  
  7.   
  8.     private int age;  
  9.     //省略 set,get方法  
  10.     }  
  11.   
  12. //  再创建一个Test类,其中在main方法中代码如下:  
  13.     import java.lang.reflect.InvocationTargetException;  
  14.     import java.util.HashMap;  
  15.     import java.util.Map;  
  16.     import org.apache.commons.beanutils.BeanUtils;  
  17.     import org.apache.commons.beanutils.ConvertUtils;  
  18.     public class Test {  
  19.   
  20.     /** 
  21.  
  22.     * @param args 
  23.  
  24.     */  
  25.     public static void main(String[] args) {  
  26.     Person person = new Person();  
  27.     person.setName("tom");  
  28.     person.setAge(21);  
  29.     try {  
  30.             //克隆  
  31.         Person person2 =  (Person)BeanUtils.cloneBean(person);  
  32.         System.out.println(person2.getName()+">>"+person2.getAge());  
  33.     } catch (IllegalAccessException e) {  
  34.         e.printStackTrace();  
  35.     } catch (InstantiationException e) {  
  36.         e.printStackTrace();  
  37.     } catch (InvocationTargetException e) {  
  38.         e.printStackTrace();  
  39.     } catch (NoSuchMethodException e) {  
  40.         e.printStackTrace();  
  41.   
  42.     }  
  43.   
  44.     }  
  45.   
  46.     }  
  47.   
  48. //  原理也是通过Java的反射机制来做的。  
  49. //  2、 将一个Map对象转化为一个Bean  
  50. //  这个Map对象的key必须与Bean的属性相对应。  
  51.     Map map = new HashMap();  
  52.     map.put("name","tom");  
  53.     map.put("email","tom@");  
  54.     map.put("age","21");  
  55.     //将map转化为一个Person对象  
  56.     Person person = new Person();  
  57.     BeanUtils.populate(person,map);  
  58. //  通过上面的一行代码,此时person的属性就已经具有了上面所赋的值了。  
  59. //  将一个Bean转化为一个Map对象了,如下:  
  60.     Map map = BeanUtils.describe(person)  

 

2、Betwixt  XML与Java对象之间相互转换。

 

Java代码   收藏代码
  1. //1、 将JavaBean转为XML内容  
  2.     // 新创建一个Person类  
  3.     public class Person{  
  4.         private String name;  
  5.         private int age;  
  6.         /** Need to allow bean to be created via reflection */  
  7.         public PersonBean() {  
  8.         }  
  9.         public PersonBean(String name, int age) {  
  10.             this.name = name;  
  11.             this.age = age;  
  12.         }  
  13.         //省略set, get方法  
  14.         public String toString() {  
  15.             return "PersonBean[name='" + name + "',age='" + age + "']";  
  16.         }  
  17.     }  
  18.       
  19.     //再创建一个WriteApp类:  
  20.     import java.io.StringWriter;  
  21.     import org.apache.commons.betwixt.io.BeanWriter;  
  22.     public class WriteApp {  
  23.     /** 
  24.     * 创建一个例子Bean,并将它转化为XML. 
  25.     */  
  26.     public static final void main(String [] args) throws Exception {  
  27.         // 先创建一个StringWriter,我们将把它写入为一个字符串         
  28.         StringWriter outputWriter = new StringWriter();  
  29.         // Betwixt在这里仅仅是将Bean写入为一个片断  
  30.         // 所以如果要想完整的XML内容,我们应该写入头格式  
  31.         outputWriter.write(“<?xml version=’1.0′ encoding=’UTF-8′ ?>\n”);  
  32.         // 创建一个BeanWriter,其将写入到我们预备的stream中  
  33.         BeanWriter beanWriter = new BeanWriter(outputWriter);  
  34.         // 配置betwixt  
  35.         // 更多详情请参考java docs 或最新的文档  
  36.         beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);  
  37.         beanWriter.getBindingConfiguration().setMapIDs(false);  
  38.         beanWriter.enablePrettyPrint();  
  39.         // 如果这个地方不传入XML的根节点名,Betwixt将自己猜测是什么  
  40.         // 但是让我们将例子Bean名作为根节点吧  
  41.         beanWriter.write(“person”, new PersonBean(“John Smith”, 21));  
  42.         //输出结果  
  43.         System.out.println(outputWriter.toString());  
  44.         // Betwixt写的是片断而不是一个文档,所以不要自动的关闭掉writers或者streams,  
  45.         //但这里仅仅是一个例子,不会做更多事情,所以可以关掉  
  46.         outputWriter.close();  
  47.         }  
  48.     }  
  49. //2、 将XML转化为JavaBean  
  50.     import java.io.StringReader;  
  51.     import org.apache.commons.betwixt.io.BeanReader;  
  52.     public class ReadApp {  
  53.     public static final void main(String args[]) throws Exception{  
  54.         // 先创建一个XML,由于这里仅是作为例子,所以我们硬编码了一段XML内容  
  55.         StringReader xmlReader = new StringReader(  
  56.         "<?xml version=’1.0′ encoding=’UTF-8′ ?> <person><age>25</age><name>James Smith</name></person>");  
  57.         //创建BeanReader  
  58.         BeanReader beanReader  = new BeanReader();  
  59.         //配置reader  
  60.         beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);  
  61.         beanReader.getBindingConfiguration().setMapIDs(false);  
  62.         //注册beans,以便betwixt知道XML将要被转化为一个什么Bean  
  63.         beanReader.registerBeanClass("person", PersonBean.class);  
  64.         //现在我们对XML进行解析  
  65.         PersonBean person = (PersonBean) beanReader.parse(xmlReader);  
  66.         //输出结果  
  67.         System.out.println(person);  
  68.         }  
  69.     }  

 

3、Codec 提供了一些公共的编解码实现,比如Base64, Hex, MD5,Phonetic and URLs等等。

 

Java代码   收藏代码
  1. //Base64编解码  
  2. private static String encodeTest(String str){  
  3.         Base64 base64 = new Base64();  
  4.         try {  
  5.             str = base64.encodeToString(str.getBytes("UTF-8"));  
  6.         } catch (UnsupportedEncodingException e) {  
  7.             e.printStackTrace();  
  8.         }  
  9.             System.out.println("Base64 编码后:"+str);  
  10.         return str;  
  11.     }  
  12.   
  13.     private static void decodeTest(String str){  
  14.         Base64 base64 = new Base64();  
  15.         //str = Arrays.toString(Base64.decodeBase64(str));  
  16.         str = new String(Base64.decodeBase64(str));  
  17.         System.out.println("Base64 解码后:"+str);  
  18.     }  

 

4、Collections 对java.util的扩展封装,处理数据还是挺灵活的。

org.apache.commons.collections – Commons Collections自定义的一组公用的接口和工具类

org.apache.commons.collections.bag – 实现Bag接口的一组类

org.apache.commons.collections.bidimap – 实现BidiMap系列接口的一组类

org.apache.commons.collections.buffer – 实现Buffer接口的一组类

org.apache.commons.collections.collection – 实现java.util.Collection接口的一组类

org.apache.commons.collections.comparators – 实现java.util.Comparator接口的一组类

org.apache.commons.collections.functors – Commons Collections自定义的一组功能类

org.apache.commons.collections.iterators – 实现java.util.Iterator接口的一组类

org.apache.commons.collections.keyvalue – 实现集合和键/值映射相关的一组类

org.apache.commons.collections.list – 实现java.util.List接口的一组类

org.apache.commons.collections.map – 实现Map系列接口的一组类

org.apache.commons.collections.set – 实现Set系列接口的一组类

Java代码   收藏代码
  1. /** 
  2.         * 得到集合里按顺序存放的key之后的某一Key 
  3.         */  
  4.         OrderedMap map = new LinkedMap();  
  5.         map.put("FIVE""5");  
  6.         map.put("SIX""6");  
  7.         map.put("SEVEN""7");  
  8.         map.firstKey(); // returns "FIVE"  
  9.         map.nextKey("FIVE"); // returns "SIX"  
  10.         map.nextKey("SIX"); // returns "SEVEN"   
  11.       
  12.         /** 
  13.         * 通过key得到value 
  14.         * 通过value得到key 
  15.         * 将map里的key和value对调 
  16.         */  
  17.       
  18.         BidiMap bidi = new TreeBidiMap();  
  19.         bidi.put("SIX""6");  
  20.         bidi.get("SIX");  // returns "6"  
  21.         bidi.getKey("6");  // returns "SIX"  
  22.         //       bidi.removeValue("6");  // removes the mapping  
  23.         BidiMap inverse = bidi.inverseBidiMap();  // returns a map with keys and values swapped  
  24.         System.out.println(inverse);  
  25.   
  26.         /** 
  27.          * 得到两个集合中相同的元素 
  28.          */  
  29.         List<String> list1 = new ArrayList<String>();  
  30.         list1.add("1");  
  31.         list1.add("2");  
  32.         list1.add("3");  
  33.         List<String> list2 = new ArrayList<String>();  
  34.         list2.add("2");  
  35.         list2.add("3");  
  36.         list2.add("5");  
  37.         Collection c = CollectionUtils.retainAll(list1, list2);  
  38.         System.out.println(c);  

 

5、Compress commons compress中的打包、压缩类库。 

 

Java代码   收藏代码
  1. //创建压缩对象  
  2.     ZipArchiveEntry entry = new ZipArchiveEntry("CompressTest");  
  3.       //要压缩的文件  
  4.       File f=new File("e:\\test.pdf");  
  5.       FileInputStream fis=new FileInputStream(f);  
  6.       //输出的对象 压缩的文件  
  7.       ZipArchiveOutputStream zipOutput=new ZipArchiveOutputStream(new File("e:\\test.zip"));    
  8.       zipOutput.putArchiveEntry(entry);  
  9.       int i=0,j;  
  10.       while((j=fis.read()) != -1)  
  11.       {   
  12.        zipOutput.write(j);  
  13.        i++;  
  14.        System.out.println(i);  
  15.       }  
  16.       zipOutput.closeArchiveEntry();  
  17.       zipOutput.close();  
  18.       fis.close();  

 

 

6、Configuration 用来帮助处理配置文件的,支持很多种存储方式。
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

Java代码   收藏代码
  1. //举一个Properties的简单例子  
  2. # usergui.properties  
  3. colors.background = #FFFFFF  
  4. colors.foreground = #000080  
  5. window.width = 500  
  6. window.height = 300  
  7.   
  8. PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");  
  9. config.setProperty("colors.background", "#000000);  
  10. config.save();  
  11.   
  12. config.save("usergui.backup.properties);//save a copy  
  13. Integer integer = config.getInteger("window.width");  

 

7、DBCP  (Database Connection Pool)是一个依赖Jakarta commons-pool对象池机制的数据库连接池,Tomcat的数据源使用的就是DBCP。

Java代码   收藏代码
  1. import javax.sql.DataSource;  
  2. import java.sql.Connection;  
  3. import java.sql.Statement;  
  4. import java.sql.ResultSet;  
  5. import java.sql.SQLException;  
  6.   
  7. import org.apache.commons.pool.ObjectPool;  
  8. import org.apache.commons.pool.impl.GenericObjectPool;  
  9. import org.apache.commons.dbcp.ConnectionFactory;  
  10. import org.apache.commons.dbcp.PoolingDataSource;  
  11. import org.apache.commons.dbcp.PoolableConnectionFactory;  
  12. import org.apache.commons.dbcp.DriverManagerConnectionFactory;  
  13. //官方示例  
  14. public class PoolingDataSources {  
  15.   
  16.     public static void main(String[] args) {  
  17.         System.out.println("加载jdbc驱动");  
  18.         try {  
  19.         Class.forName("oracle.jdbc.driver.OracleDriver");  
  20.         } catch (ClassNotFoundException e) {  
  21.         e.printStackTrace();  
  22.         }  
  23.         System.out.println("Done.");  
  24.         //  
  25.         System.out.println("设置数据源");  
  26.         DataSource dataSource = setupDataSource("jdbc:oracle:thin:@localhost:1521:test");  
  27.         System.out.println("Done.");  
  28.           
  29.         //  
  30.         Connection conn = null;  
  31.         Statement stmt = null;  
  32.         ResultSet rset = null;  
  33.           
  34.         try {  
  35.         System.out.println("Creating connection.");  
  36.         conn = dataSource.getConnection();  
  37.         System.out.println("Creating statement.");  
  38.         stmt = conn.createStatement();  
  39.         System.out.println("Executing statement.");  
  40.         rset = stmt.executeQuery("select * from person");  
  41.         System.out.println("Results:");  
  42.         int numcols = rset.getMetaData().getColumnCount();  
  43.         while(rset.next()) {  
  44.         for(int i=0;i<=numcols;i++) {  
  45.         System.out.print("\t" + rset.getString(i));  
  46.         }  
  47.         System.out.println("");  
  48.         }  
  49.         } catch(SQLException e) {  
  50.         e.printStackTrace();  
  51.         } finally {  
  52.         try { if (rset != null) rset.close(); } catch(Exception e) { }  
  53.         try { if (stmt != null) stmt.close(); } catch(Exception e) { }  
  54.         try { if (conn != null) conn.close(); } catch(Exception e) { }  
  55.         }  
  56.         }  
  57.   
  58.     public static DataSource setupDataSource(String connectURI) {  
  59.         //设置连接地址  
  60.         ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(  
  61.                 connectURI, null);  
  62.   
  63.         // 创建连接工厂  
  64.         PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(  
  65.                 connectionFactory);  
  66.   
  67.         //获取GenericObjectPool 连接的实例  
  68.         ObjectPool connectionPool = new GenericObjectPool(  
  69.                 poolableConnectionFactory);  
  70.   
  71.         // 创建 PoolingDriver  
  72.         PoolingDataSource dataSource = new PoolingDataSource(connectionPool);  
  73.           
  74.         return dataSource;  
  75.     }  
  76. }  

 

8、DbUtils Apache组织提供的一个资源JDBC工具类库,它是对JDBC的简单封装,对传统操作数据库的类进行二次封装,可以把结果集转化成List。,同时也不影响程序的性能。

DbUtils类:启动类
ResultSetHandler接口:转换类型接口
MapListHandler类:实现类,把记录转化成List
BeanListHandler类:实现类,把记录转化成List,使记录为JavaBean类型的对象
Qrery Runner类:执行SQL语句的类

Java代码   收藏代码
  1. import org.apache.commons.dbutils.DbUtils;  
  2. import org.apache.commons.dbutils.QueryRunner;  
  3. import org.apache.commons.dbutils.handlers.BeanListHandler;  
  4. import java.sql.Connection;  
  5. import java.sql.DriverManager;  
  6. import java.sql.SQLException;  
  7. import java.util.List;  
  8. //转换成list  
  9. public class BeanLists {  
  10.     public static void main(String[] args) {  
  11.         Connection conn = null;  
  12.         String url = "jdbc:mysql://localhost:3306/ptest";  
  13.         String jdbcDriver = "com.mysql.jdbc.Driver";  
  14.         String user = "root";  
  15.         String password = "ptest";  
  16.   
  17.         DbUtils.loadDriver(jdbcDriver);  
  18.         try {  
  19.             conn = DriverManager.getConnection(url, user, password);  
  20.             QueryRunner qr = new QueryRunner();  
  21.             List results = (List) qr.query(conn, "select id,name from person"new BeanListHandler(Person.class));  
  22.             for (int i = 0; i < results.size(); i++) {  
  23.                 Person p = (Person) results.get(i);  
  24.                 System.out.println("id:" + p.getId() + ",name:" + p.getName());  
  25.             }  
  26.         } catch (SQLException e) {  
  27.             e.printStackTrace();  
  28.         } finally {  
  29.             DbUtils.closeQuietly(conn);  
  30.         }  
  31.     }  
  32. }  
  33.   
  34. public class Person{  
  35.     private Integer id;  
  36.     private String name;  
  37.   
  38.    //省略set, get方法  
  39. }  
  40.   
  41. import org.apache.commons.dbutils.DbUtils;  
  42. import org.apache.commons.dbutils.QueryRunner;  
  43. import org.apache.commons.dbutils.handlers.MapListHandler;  
  44.   
  45. import java.sql.Connection;  
  46. import java.sql.DriverManager;  
  47. import java.sql.SQLException;  
  48.   
  49. import java.util.List;  
  50. import java.util.Map;  
  51. //转换成map  
  52. public class MapLists {  
  53.     public static void main(String[] args) {  
  54.         Connection conn = null;  
  55.         String url = "jdbc:mysql://localhost:3306/ptest";  
  56.         String jdbcDriver = "com.mysql.jdbc.Driver";  
  57.         String user = "root";  
  58.         String password = "ptest";  
  59.   
  60.         DbUtils.loadDriver(jdbcDriver);  
  61.         try {  
  62.             conn = DriverManager.getConnection(url, user, password);  
  63.             QueryRunner qr = new QueryRunner();  
  64.             List results = (List) qr.query(conn, "select id,name from person"new MapListHandler());  
  65.             for (int i = 0; i < results.size(); i++) {  
  66.                 Map map = (Map) results.get(i);  
  67.                 System.out.println("id:" + map.get("id") + ",name:" + map.get("name"));  
  68.             }  
  69.         } catch (SQLException e) {  
  70.             e.printStackTrace();  
  71.         } finally {  
  72.             DbUtils.closeQuietly(conn);  
  73.         }  
  74.     }  
  75. }  

 

9、Email 提供的一个开源的API,是对javamail的封装。

 

Java代码   收藏代码
  1. //用commons email发送邮件  
  2. public static void main(String args[]){  
  3.         Email email = new SimpleEmail();  
  4.         email.setHostName("smtp.googlemail.com");  
  5.         email.setSmtpPort(465);  
  6.         email.setAuthenticator(new DefaultAuthenticator("username""password"));  
  7.         email.setSSLOnConnect(true);  
  8.         email.setFrom("user@gmail.com");  
  9.         email.setSubject("TestMail");  
  10.         email.setMsg("This is a test mail ... :-)");  
  11.         email.addTo("foo@bar.com");  
  12.         email.send();  
  13.     }  

 

10、FileUpload java web文件上传功能。

Java代码   收藏代码
  1. //官方示例:  
  2. //* 检查请求是否含有上传文件  
  3.     // Check that we have a file upload request  
  4.     boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
  5.   
  6.     //现在我们得到了items的列表  
  7.   
  8.     //如果你的应用近于最简单的情况,上面的处理就够了。但我们有时候还是需要更多的控制。  
  9.     //下面提供了几种控制选择:  
  10.     // Create a factory for disk-based file items  
  11.     DiskFileItemFactory factory = new DiskFileItemFactory();  
  12.   
  13.     // Set factory constraints  
  14.     factory.setSizeThreshold(yourMaxMemorySize);  
  15.     factory.setRepository(yourTempDirectory);  
  16.   
  17.     // Create a new file upload handler  
  18.     ServletFileUpload upload = new ServletFileUpload(factory);  
  19.   
  20.     // 设置最大上传大小  
  21.     upload.setSizeMax(yourMaxRequestSize);  
  22.   
  23.     // 解析所有请求  
  24.     List /* FileItem */ items = upload.parseRequest(request);  
  25.   
  26.     // Create a factory for disk-based file items  
  27.     DiskFileItemFactory factory = new DiskFileItemFactory(  
  28.             yourMaxMemorySize, yourTempDirectory);  
  29.   
  30.     //一旦解析完成,你需要进一步处理item的列表。  
  31.     // Process the uploaded items  
  32.     Iterator iter = items.iterator();  
  33.     while (iter.hasNext()) {  
  34.         FileItem item = (FileItem) iter.next();  
  35.   
  36.         if (item.isFormField()) {  
  37.             processFormField(item);  
  38.         } else {  
  39.             processUploadedFile(item);  
  40.         }  
  41.     }  
  42.   
  43.     //区分数据是否为简单的表单数据,如果是简单的数据:  
  44.     // processFormField  
  45.     if (item.isFormField()) {  
  46.         String name = item.getFieldName();  
  47.         String value = item.getString();  
  48.         //...省略步骤  
  49.     }  
  50.   
  51.     //如果是提交的文件:  
  52.     // processUploadedFile  
  53.     if (!item.isFormField()) {  
  54.         String fieldName = item.getFieldName();  
  55.         String fileName = item.getName();  
  56.         String contentType = item.getContentType();  
  57.         boolean isInMemory = item.isInMemory();  
  58.         long sizeInBytes = item.getSize();  
  59.         //...省略步骤  
  60.     }  
  61.   
  62.     //对于这些item,我们通常要把它们写入文件,或转为一个流  
  63.     // Process a file upload  
  64.     if (writeToFile) {  
  65.         File uploadedFile = new File(...);  
  66.         item.write(uploadedFile);  
  67.     } else {  
  68.         InputStream uploadedStream = item.getInputStream();  
  69.         //...省略步骤  
  70.         uploadedStream.close();  
  71.     }  
  72.   
  73.     //或转为字节数组保存在内存中:  
  74.     // Process a file upload in memory  
  75.     byte[] data = item.get();  
  76.     //...省略步骤  
  77.     //如果这个文件真的很大,你可能会希望向用户报告到底传了多少到服务端,让用户了解上传的过程  
  78.     //Create a progress listener  
  79.     ProgressListener progressListener = new ProgressListener(){  
  80.        public void update(long pBytesRead, long pContentLength, int pItems) {  
  81.            System.out.println("We are currently reading item " + pItems);  
  82.            if (pContentLength == -1) {  
  83.                System.out.println("So far, " + pBytesRead + " bytes have been read.");  
  84.            } else {  
  85.                System.out.println("So far, " + pBytesRead + " of " + pContentLength  
  86.                                   + " bytes have been read.");  
  87.            }  
  88.        }  
  89.     };  
  90.     upload.setProgressListener(progressListener);  

 

11、HttpClien 基于HttpCore实 现的一个HTTP/1.1兼容的HTTP客户端,它提供了一系列可重用的客户端身份验证、HTTP状态保持、HTTP连接管理module。

Java代码   收藏代码
  1. //GET方法  
  2. import java.io.IOException;  
  3. import org.apache.commons.httpclient.*;  
  4. import org.apache.commons.httpclient.methods.GetMethod;  
  5. import org.apache.commons.httpclient.params.HttpMethodParams;  
  6.   
  7. public class GetSample{  
  8.     public static void main(String[] args) {  
  9.         // 构造HttpClient的实例  
  10.         HttpClient httpClient = new HttpClient();  
  11.         // 创建GET方法的实例  
  12.         GetMethod getMethod = new GetMethod("http://www.ibm.com");  
  13.         // 使用系统提供的默认的恢复策略  
  14.         getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,  
  15.                 new DefaultHttpMethodRetryHandler());  
  16.         try {  
  17.             // 执行getMethod  
  18.             int statusCode = httpClient.executeMethod(getMethod);  
  19.             if (statusCode != HttpStatus.SC_OK) {  
  20.                 System.err.println("Method failed: "  
  21.                         + getMethod.getStatusLine());  
  22.             }  
  23.             // 读取内容  
  24.             byte[] responseBody = getMethod.getResponseBody();  
  25.             // 处理内容  
  26.             System.out.println(new String(responseBody));  
  27.         } catch (HttpException e) {  
  28.             // 发生致命的异常,可能是协议不对或者返回的内容有问题  
  29.             System.out.println("Please check your provided http address!");  
  30.             e.printStackTrace();  
  31.         } catch (IOException e) {  
  32.             // 发生网络异常  
  33.             e.printStackTrace();  
  34.         } finally {  
  35.             // 释放连接  
  36.             getMethod.releaseConnection();  
  37.         }  
  38.     }  
  39. }  
  40.   
  41. //POST方法  
  42. import java.io.IOException;  
  43. import org.apache.commons.httpclient.*;  
  44. import org.apache.commons.httpclient.methods.PostMethod;  
  45. import org.apache.commons.httpclient.params.HttpMethodParams;  
  46.   
  47. public class PostSample{  
  48.     public static void main(String[] args) {  
  49.         // 构造HttpClient的实例  
  50.         HttpClient httpClient = new HttpClient();  
  51.         // 创建POST方法的实例  
  52.         String url = "http://www.oracle.com/";  
  53.         PostMethod postMethod = new PostMethod(url);  
  54.         // 填入各个表单域的值  
  55.         NameValuePair[] data = { new NameValuePair("id""youUserName"),  
  56.         new NameValuePair("passwd""yourPwd") };  
  57.         // 将表单的值放入postMethod中  
  58.         postMethod.setRequestBody(data);  
  59.         // 执行postMethod  
  60.         int statusCode = httpClient.executeMethod(postMethod);  
  61.         // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发  
  62.         // 301或者302  
  63.         if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||   
  64.         statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
  65.             // 从头中取出转向的地址  
  66.             Header locationHeader = postMethod.getResponseHeader("location");  
  67.             String location = null;  
  68.             if (locationHeader != null) {  
  69.              location = locationHeader.getValue();  
  70.              System.out.println("The page was redirected to:" + location);  
  71.             } else {  
  72.              System.err.println("Location field value is null.");  
  73.             }  
  74.             return;  
  75.         }  
  76.     }  
  77. }  

 

12、IO 对java.io的扩展 操作文件非常方便。

 

Java代码   收藏代码
  1. //1.读取Stream  
  2.   
  3. //标准代码:  
  4. InputStream in = new URL( "http://jakarta.apache.org" ).openStream();  
  5. try {  
  6.        InputStreamReader inR = new InputStreamReader( in );  
  7.        BufferedReader buf = new BufferedReader( inR );  
  8.        String line;  
  9.        while ( ( line = buf.readLine() ) != null ) {  
  10.           System.out.println( line );  
  11.        }  
  12.   } finally {  
  13.     in.close();  
  14.   }  
  15.   
  16. //使用IOUtils  
  17.   
  18. InputStream in = new URL( "http://jakarta.apache.org" ).openStream();  
  19. try {  
  20.     System.out.println( IOUtils.toString( in ) );  
  21. finally {  
  22.     IOUtils.closeQuietly(in);  
  23. }  
  24.   
  25. //2.读取文件  
  26. File file = new File("/commons/io/project.properties");  
  27. List lines = FileUtils.readLines(file, "UTF-8");  
  28. //3.察看剩余空间  
  29. long freeSpace = FileSystemUtils.freeSpace("C:/");  

 

13、Lang 主要是一些公共的工具集合,比如对字符、数组的操作等等。

Java代码   收藏代码
  1. // 1 合并两个数组: org.apache.commons.lang. ArrayUtils  
  2.     // 有时我们需要将两个数组合并为一个数组,用ArrayUtils就非常方便,示例如下:  
  3.     private static void testArr() {  
  4.         String[] s1 = new String[] { "1""2""3" };  
  5.         String[] s2 = new String[] { "a""b""c" };  
  6.         String[] s = (String[]) ArrayUtils.addAll(s1, s2);  
  7.         for (int i = 0; i < s.length; i++) {  
  8.             System.out.println(s[i]);  
  9.         }  
  10.         String str = ArrayUtils.toString(s);  
  11.         str = str.substring(1, str.length() - 1);  
  12.         System.out.println(str + ">>" + str.length());  
  13.   
  14.     }  
  15.     //2 截取从from开始字符串  
  16.     StringUtils.substringAfter("SELECT * FROM PERSON ""from");  
  17.     //3 判断该字符串是不是为数字(0~9)组成,如果是,返回true 但该方法不识别有小数点和 请注意  
  18.     StringUtils.isNumeric("454534"); //返回true  
  19.     //4.取得类名  
  20.        System.out.println(ClassUtils.getShortClassName(Test.class));  
  21.        //取得其包名  
  22.        System.out.println(ClassUtils.getPackageName(Test.class));  
  23.         
  24.        //5.NumberUtils  
  25.        System.out.println(NumberUtils.stringToInt("6"));  
  26.        //6.五位的随机字母和数字  
  27.        System.out.println(RandomStringUtils.randomAlphanumeric(5));  
  28.        //7.StringEscapeUtils  
  29.        System.out.println(StringEscapeUtils.escapeHtml("<html>"));  
  30.        //输出结果为&lt;html&gt;  
  31.        System.out.println(StringEscapeUtils.escapeJava("String"));  
  32.         
  33.        //8.StringUtils,判断是否是空格字符  
  34.        System.out.println(StringUtils.isBlank("   "));  
  35.        //将数组中的内容以,分隔  
  36.        System.out.println(StringUtils.join(test,","));  
  37.        //在右边加下字符,使之总长度为6  
  38.        System.out.println(StringUtils.rightPad("abc"6'T'));  
  39.        //首字母大写  
  40.        System.out.println(StringUtils.capitalize("abc"));  
  41.        //Deletes all whitespaces from a String 删除所有空格  
  42.        System.out.println( StringUtils.deleteWhitespace("   ab  c  "));  
  43.        //判断是否包含这个字符  
  44.        System.out.println( StringUtils.contains("abc""ba"));  
  45.        //表示左边两个字符  
  46.        System.out.println( StringUtils.left("abc"2));  
  47.        System.out.println(NumberUtils.stringToInt("33"));  

 

14、Logging 提供的是一个Java 的日志接口,同时兼顾轻量级和不依赖于具体的日志实现工具。

 

Java代码   收藏代码
  1. import org.apache.commons.logging.Log;  
  2. import org.apache.commons.logging.LogFactory;  
  3.   
  4.     public class CommonLogTest {  
  5.      private static Log log = LogFactory.getLog(CommonLogTest.class);  
  6.      //日志打印  
  7.      public static void main(String[] args) {  
  8.          log.error("ERROR");  
  9.          log.debug("DEBUG");  
  10.          log.warn("WARN");  
  11.          log.info("INFO");  
  12.          log.trace("TRACE");  
  13.       System.out.println(log.getClass());  
  14.      }  
  15.   
  16.     }  

 


15、Validator 
通用验证系统,该组件提供了客户端和服务器端的数据验证框架。 

 验证日期

Java代码   收藏代码
  1. // 获取日期验证  
  2.       DateValidator validator = DateValidator.getInstance();  
  3.   
  4.       // 验证/转换日期  
  5.       Date fooDate = validator.validate(fooString, "dd/MM/yyyy");  
  6.       if (fooDate == null) {  
  7.           // 错误 不是日期  
  8.           return;  
  9.       }  

表达式验证

Java代码   收藏代码
  1. // 设置参数  
  2.       boolean caseSensitive = false;  
  3.       String regex1   = "^([A-Z]*)(?:\\-)([A-Z]*)*$"  
  4.       String regex2   = "^([A-Z]*)$";  
  5.       String[] regexs = new String[] {regex1, regex1};  
  6.   
  7.       // 创建验证  
  8.       RegexValidator validator = new RegexValidator(regexs, caseSensitive);  
  9.   
  10.       // 验证返回boolean  
  11.       boolean valid = validator.isValid("abc-def");  
  12.   
  13.       // 验证返回字符串  
  14.       String result = validator.validate("abc-def");  
  15.   
  16.       // 验证返回数组  
  17.       String[] groups = validator.match("abc-def");  

 配置文件中使用验证

Xml代码   收藏代码
  1. <form-validation>  
  2.    <global>  
  3.        <validator name="required"  
  4.           classname="org.apache.commons.validator.TestValidator"  
  5.           method="validateRequired"  
  6.           methodParams="java.lang.Object, org.apache.commons.validator.Field"/>  
  7.     </global>  
  8.     <formset>  
  9.     </formset>  
  10. </form-validation>  
  11.   
  12. 添加姓名验证.  
  13.   
  14. <form-validation>  
  15.    <global>  
  16.        <validator name="required"  
  17.           classname="org.apache.commons.validator.TestValidator"  
  18.           method="validateRequired"  
  19.           methodParams="java.lang.Object, org.apache.commons.validator.Field"/>  
  20.     </global>  
  21.     <formset>  
  22.        <form name="nameForm">  
  23.           <field property="firstName" depends="required">  
  24.              <arg0 key="nameForm.firstname.displayname"/>  
  25.           </field>  
  26.           <field property="lastName" depends="required">  
  27.              <arg0 key="nameForm.lastname.displayname"/>  
  28.           </field>  
  29.        </form>  
  30.     </formset>  
  31. </form-validation>   

 验证类

Java代码   收藏代码
  1.  Excerpts from org.apache.commons.validator.RequiredNameTest  
  2. //加载验证配置文件  
  3. InputStream in = this.getClass().getResourceAsStream("validator-name-required.xml");  
  4.   
  5. ValidatorResources resources = new ValidatorResources(in);  
  6. //这个是自己创建的bean 我这里省略了  
  7. Name name = new Name();  
  8.   
  9. Validator validator = new Validator(resources, "nameForm");  
  10. //设置参数  
  11. validator.setParameter(Validator.BEAN_PARAM, name);  
  12.   
  13.   
  14. Map results = null;  
  15. //验证  
  16. results = validator.validate();  
  17.   
  18. if (results.get("firstName") == null) {  
  19.     //验证成功  
  20. else {  
  21.     //有错误     int errors = ((Integer)results.get("firstName")).intValue();  
  22. }   

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值