Apache Commons 工具類介紹及簡單使用

  Apache Commons包含了不少開源的工具,用於解決平時編程常常會遇到的問題,減小重複勞動。下面是我這幾年作開發過程當中本身用過的工具類作簡單介紹。html

 

組件 功能介紹
BeanUtils 提供了對於JavaBean進行各類操做,克隆對象,屬性等等.
Betwixt XML與Java對象之間相互轉換.
Codec 處理經常使用的編碼方法的工具類包 例如DES、SHA一、MD五、Base64等.
Collections java集合框架操做.
Compress java提供文件打包 壓縮類庫.
Configuration 一個java應用程序的配置管理類庫.
DBCP 提供數據庫鏈接池服務.
DbUtils 提供對jdbc 的操做封裝來簡化數據查詢和記錄讀取操做.
Email java發送郵件 對javamail的封裝.
FileUpload 提供文件上傳功能.
HttpClien 提供HTTP客戶端與服務器的各類通信操做. 如今已改爲HttpComponents
IO io工具的封裝.
Lang Java基本對象方法的工具類包 如:StringUtils,ArrayUtils等等.
Logging 提供的是一個Java 的日誌接口.
Validator 提供了客戶端和服務器端的數據驗證框架.

一、BeanUtils 

提供了對於JavaBean進行各類操做, 好比對象,屬性複製等等。java

 

Java代碼   收藏代碼
  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. //  二、 將一個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)  

 

二、Betwixt  

XML與Java對象之間相互轉換。
mysql

 

Java代碼   收藏代碼
  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. //二、 將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.     }  

 

三、Codec 

提供了一些公共的編解碼實現,好比Base64, Hex, MD5,Phonetic and URLs等等。web

 

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.     }  

 

四、Collections

 對java.util的擴展封裝,處理數據仍是挺靈活的。
sql

org.apache.commons.collections – Commons Collections自定義的一組公用的接口和工具類數據庫

org.apache.commons.collections.bag – 實現Bag接口的一組類apache

org.apache.commons.collections.bidimap – 實現BidiMap系列接口的一組類編程

org.apache.commons.collections.buffer – 實現Buffer接口的一組類api

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);  

 

五、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();  

 

 

六、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");  

 

七、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. }  

 

八、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. }  

 

九、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.     }  

 

十、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);  

 

十一、HttpClient

 基於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. }  

 

十二、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:/");  

 

1三、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"));  

 

1四、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.     }  

 


1五、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. }   
相關文章
相關標籤/搜索