Apache Commons 工具类介绍及简单使用


目录(?) [-]
  1. commons-beanutils 
  2. commons-betwixt  
  3. commons-codec 
  4. commons-collections
  5. commons-compress 
  6. commons-configuration
  7. commons-dbcp
  8. commons-dbutils 
  9. commons-email 
  10. commons-fileupload
  11. commons-httpclient
  12. commons-io
  13. commos-lang 
  14. commos-logging
  15. Validator 

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

组件 功能介绍
commons-beanutils 提供了对于JavaBean进行各种操作,克隆对象,属性等等.
commons-betwixt XML与Java对象之间相互转换.
commons-codec 处理常用的编码方法的工具类包 例如DES、SHA1、MD5、Base64等.
commons-collections java集合框架操作.
commons-compress java提供文件打包 压缩类库.
commons-configuration 一个java应用程序的配置管理类库.
commons-dbcp 提供数据库连接池服务.
commons-dbutils 提供对jdbc 的操作封装来简化数据查询和记录读取操作.
commons-email java发送邮件 对javamail的封装.
commons-fileupload 提供文件上传功能.
commons-httpclient 提供HTTP客户端与服务器的各种通讯操作. 现在已改成HttpComponents
commons-io io工具的封装.
commons-lang Java基本对象方法的工具类包 如:StringUtils,ArrayUtils,DateUtils,DateFormatUtils等等.
commons-logging 提供的是一个Java 的日志接口.
commons-validator 提供了客户端和服务器端的数据验证框架.

1、commons-beanutils 

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

 Java代码  收藏代码

  1. import java.util.HashMap;  
  2. import java.util.Map;  
  3. import org.apache.commons.beanutils.BeanUtils;  
  4. import org.apache.commons.beanutils.PropertyUtils;  
  5.   
  6. public class CommonsBeanUtils {  
  7.     public static void main(String[] args) throws Exception {  
  8.         // ****************************************************************************  
  9.         Person person = new Person();  
  10.         person.setName("tom");  
  11.         person.setAge(21);  
  12.         // 克隆对象  
  13.         Person person2 = (Person) BeanUtils.cloneBean(person);  
  14.         System.out.println(person2.getName() + ">>" + person2.getAge());  
  15.         // ****************************************************************************  
  16.         Map<String, String> map = new HashMap<String, String>();  
  17.         map.put("name""tom");  
  18.         map.put("email""tom@");  
  19.         map.put("age""21");  
  20.         // 将map转化为一个Person对象  
  21.         Person person3 = new Person();  
  22.         BeanUtils.populate(person3, map);  
  23.         System.out.println(person3.getName() + ">>" + person3.getAge());  
  24.         // 通过上面的一行代码,此时person的属性就已经具有了上面所赋的值了。  
  25.         // 将一个Bean转化为一个Map对象了,如下:  
  26.         Map<String, String> map2 = BeanUtils.describe(person3);  
  27.         System.out.println(map2.get("name") + ">>" + map2.get("age"));  
  28.         // ****************************************************************************  
  29.         Person person4 = new Person();  
  30.         person4.setName("andy");  
  31.         // 反射调用get方法  
  32.         String name = (String) PropertyUtils.getProperty(person4, "name");  
  33.         System.out.println(name);  
  34.         // 反射调用set方法  
  35.         PropertyUtils.setProperty(person4, "age"25);  
  36.         System.out.println(person4.getAge());  
  37.     }  
  38. }  
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class CommonsBeanUtils {
	public static void main(String[] args) throws Exception {
		// ****************************************************************************
		Person person = new Person();
		person.setName("tom");
		person.setAge(21);
		// 克隆对象
		Person person2 = (Person) BeanUtils.cloneBean(person);
		System.out.println(person2.getName() + ">>" + person2.getAge());
		// ****************************************************************************
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", "tom");
		map.put("email", "tom@");
		map.put("age", "21");
		// 将map转化为一个Person对象
		Person person3 = new Person();
		BeanUtils.populate(person3, map);
		System.out.println(person3.getName() + ">>" + person3.getAge());
		// 通过上面的一行代码,此时person的属性就已经具有了上面所赋的值了。
		// 将一个Bean转化为一个Map对象了,如下:
		Map<String, String> map2 = BeanUtils.describe(person3);
		System.out.println(map2.get("name") + ">>" + map2.get("age"));
		// ****************************************************************************
		Person person4 = new Person();
		person4.setName("andy");
		// 反射调用get方法
		String name = (String) PropertyUtils.getProperty(person4, "name");
		System.out.println(name);
		// 反射调用set方法
		PropertyUtils.setProperty(person4, "age", 25);
		System.out.println(person4.getAge());
	}
}

2、commons-betwixt  

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

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

public class CommonsBetwixt {
	public static void main(String[] args) throws Exception {
		// ****************************创建一个例子Bean,并将它转化为XML ************************************************
		// 先创建一个StringWriter,我们将把它写入为一个字符串
		StringWriter outputWriter = new StringWriter();
		// Betwixt在这里仅仅是将Bean写入为一个片断
		// 所以如果要想完整的XML内容,我们应该写入头格式
		outputWriter.write("<?xml version=’1.0′ encoding=’UTF-8′ ?>\n");
		// 创建一个BeanWriter,其将写入到我们预备的stream中
		BeanWriter beanWriter = new BeanWriter(outputWriter);
		// 配置betwixt
		// 更多详情请参考java docs 或最新的文档
		beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
		beanWriter.getBindingConfiguration().setMapIDs(false);
		beanWriter.enablePrettyPrint();
		// 如果这个地方不传入XML的根节点名,Betwixt将自己猜测是什么
		// 但是让我们将例子Bean名作为根节点吧
		beanWriter.write("person", new Person("John Smith", 21));
		// 输出结果
		System.out.println(outputWriter.toString());
		// Betwixt写的是片断而不是一个文档,所以不要自动的关闭掉writers或者streams,
		// 但这里仅仅是一个例子,不会做更多事情,所以可以关掉
		outputWriter.close();
		// ****************************将XML转化为JavaBean ************************************************
		// 先创建一个XML,由于这里仅是作为例子,所以我们硬编码了一段XML内容
		StringReader xmlReader = new StringReader("<?xml version='1.0' encoding='UTF-8' ?> <person><age>25</age><name>James Smith</name></person>");
		// 创建BeanReader
		BeanReader beanReader = new BeanReader();
		// 配置reader
		beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
		beanReader.getBindingConfiguration().setMapIDs(false);
		// 注册beans,以便betwixt知道XML将要被转化为一个什么Bean
		beanReader.registerBeanClass("person", Person.class);
		// 现在我们对XML进行解析
		Person person = (Person) beanReader.parse(xmlReader);
		// 输出结果
		System.out.println(person);
	}
}

3、commons-codec 

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

 

Java代码   收藏代码
  1. import org.apache.commons.codec.binary.Base64;  
  2.   
  3. public class CommonsCodec {  
  4.     public static void main(String[] args) throws Exception {  
  5.         Base64 base64 = new Base64();  
  6.         String encodestr = base64.encodeToString("abcd".getBytes("UTF-8"));  
  7.         System.out.println("Base64 编码后:" + encodestr);  
  8.           
  9.         String decodestr = new String(Base64.decodeBase64("YWJjZA=="));    
  10.         System.out.println("Base64 解码后:"+decodestr);    
  11.     }  
  12. }  
import org.apache.commons.codec.binary.Base64;

public class CommonsCodec {
	public static void main(String[] args) throws Exception {
		Base64 base64 = new Base64();
		String encodestr = base64.encodeToString("abcd".getBytes("UTF-8"));
		System.out.println("Base64 编码后:" + encodestr);
		
		String decodestr = new String(Base64.decodeBase64("YWJjZA=="));  
        System.out.println("Base64 解码后:"+decodestr);  
	}
}

4、commons-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. import java.util.ArrayList;  
  2. import java.util.Collection;  
  3. import java.util.List;  
  4.   
  5. import org.apache.commons.collections.BidiMap;  
  6. import org.apache.commons.collections.CollectionUtils;  
  7. import org.apache.commons.collections.OrderedMap;  
  8. import org.apache.commons.collections.bidimap.TreeBidiMap;  
  9. import org.apache.commons.collections.map.LinkedMap;  
  10.   
  11. public class CommonsCollections {  
  12.     public static void main(String[] args) {  
  13.         //得到集合里按顺序存放的key之后的某一Key  
  14.         OrderedMap map = new LinkedMap ();  
  15.         map.put("FIVE""5");  
  16.         map.put("SIX""6");  
  17.         map.put("SEVEN""7");  
  18.         map.firstKey(); // returns "FIVE"  
  19.         map.nextKey("FIVE"); // returns "SIX"  
  20.         map.nextKey("SIX"); // returns "SEVEN"  
  21.   
  22.         //通过key得到value 通过value得到key 将map里的key和value对调  
  23.         BidiMap bidi = new TreeBidiMap();  
  24.         bidi.put("SIX""6");  
  25.         bidi.get("SIX"); // returns "6"  
  26.         bidi.getKey("6"); // returns "SIX"  
  27.         // bidi.removeValue("6"); // removes the mapping  
  28.         BidiMap inverse = bidi.inverseBidiMap(); // returns a map with keys and values swapped  
  29.         System.out.println(inverse);  
  30.   
  31.         //得到两个集合中相同的元素  
  32.         List<String> list1 = new ArrayList<String>();  
  33.         list1.add("1");  
  34.         list1.add("2");  
  35.         list1.add("3");  
  36.         List<String> list2 = new ArrayList<String>();  
  37.         list2.add("2");  
  38.         list2.add("3");  
  39.         list2.add("5");  
  40.         Collection c = CollectionUtils.retainAll(list1, list2);  
  41.         System.out.println(c);  
  42.     }  
  43. }  
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.OrderedMap;
import org.apache.commons.collections.bidimap.TreeBidiMap;
import org.apache.commons.collections.map.LinkedMap;

public class CommonsCollections {
	public static void main(String[] args) {
		//得到集合里按顺序存放的key之后的某一Key
		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"

		//通过key得到value 通过value得到key 将map里的key和value对调
		BidiMap bidi = new TreeBidiMap();
		bidi.put("SIX", "6");
		bidi.get("SIX"); // returns "6"
		bidi.getKey("6"); // returns "SIX"
		// bidi.removeValue("6"); // removes the mapping
		BidiMap inverse = bidi.inverseBidiMap(); // returns a map with keys and values swapped
		System.out.println(inverse);

		//得到两个集合中相同的元素
		List<String> list1 = new ArrayList<String>();
		list1.add("1");
		list1.add("2");
		list1.add("3");
		List<String> list2 = new ArrayList<String>();
		list2.add("2");
		list2.add("3");
		list2.add("5");
		Collection c = CollectionUtils.retainAll(list1, list2);
		System.out.println(c);
	}
}

5、commons-compress 

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

 

Java代码   收藏代码
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3.   
  4. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;  
  5. import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;  
  6.   
  7. public class CommonsCompress {  
  8.     public static void main(String[] args) throws Exception {  
  9.         // 创建压缩对象  
  10.         ZipArchiveEntry entry = new ZipArchiveEntry("CompressTest");  
  11.         // 要压缩的文件  
  12.         File f = new File("e:\\test.pdf");  
  13.         FileInputStream fis = new FileInputStream(f);  
  14.         // 输出的对象 压缩的文件  
  15.         ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new File("e:\\test.zip"));  
  16.         zipOutput.putArchiveEntry(entry);  
  17.         int i = 0, j;  
  18.         while ((j = fis.read()) != -1) {  
  19.             zipOutput.write(j);  
  20.             i++;  
  21.             System.out.println(i);  
  22.         }  
  23.         zipOutput.closeArchiveEntry();  
  24.         zipOutput.close();  
  25.         fis.close();  
  26.     }  
  27. }  
import java.io.File;
import java.io.FileInputStream;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;

public class CommonsCompress {
	public static void main(String[] args) throws Exception {
		// 创建压缩对象
		ZipArchiveEntry entry = new ZipArchiveEntry("CompressTest");
		// 要压缩的文件
		File f = new File("e:\\test.pdf");
		FileInputStream fis = new FileInputStream(f);
		// 输出的对象 压缩的文件
		ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new File("e:\\test.zip"));
		zipOutput.putArchiveEntry(entry);
		int i = 0, j;
		while ((j = fis.read()) != -1) {
			zipOutput.write(j);
			i++;
			System.out.println(i);
		}
		zipOutput.closeArchiveEntry();
		zipOutput.close();
		fis.close();
	}
}

 

6、commons-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、commons-dbcp

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

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

public class CommonsDbcp {
	public static void main(String[] args) {
		System.out.println("加载jdbc驱动");
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println("Done.");
		//
		System.out.println("设置数据源");
		DataSource dataSource = setupDataSource("jdbc:oracle:thin:@localhost:1521:test");
		System.out.println("Done.");

		//
		Connection conn = null;
		Statement stmt = null;
		ResultSet rset = null;

		try {
			System.out.println("Creating connection.");
			conn = dataSource.getConnection();
			System.out.println("Creating statement.");
			stmt = conn.createStatement();
			System.out.println("Executing statement.");
			rset = stmt.executeQuery("select * from person");
			System.out.println("Results:");
			int numcols = rset.getMetaData().getColumnCount();
			while (rset.next()) {
				for (int i = 0; i <= numcols; i++) {
					System.out.print("\t" + rset.getString(i));
				}
				System.out.println("");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rset != null)
					rset.close();
			} catch (Exception e) {
			}
			try {
				if (stmt != null)
					stmt.close();
			} catch (Exception e) {
			}
			try {
				if (conn != null)
					conn.close();
			} catch (Exception e) {
			}
		}
	}

	public static DataSource setupDataSource(String connectURI) {
		// 设置连接地址
		ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, null);

		// 创建连接工厂
		PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null, null, connectURI, false, false);

		// 获取GenericObjectPool 连接的实例
		ObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory);

		// 创建 PoolingDriver
		PoolingDataSource dataSource = new PoolingDataSource(connectionPool);

		return dataSource;
	}
}

8、commons-dbutils 

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

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

Java代码   收藏代码
  1. import java.sql.Connection;  
  2. import java.sql.DriverManager;  
  3. import java.sql.SQLException;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import org.apache.commons.dbutils.DbUtils;  
  7. import org.apache.commons.dbutils.QueryRunner;  
  8. import org.apache.commons.dbutils.handlers.BeanListHandler;  
  9. import org.apache.commons.dbutils.handlers.MapListHandler;  
  10.   
  11. public class CommonsDbutils {  
  12.   
  13.     public static void main(String[] args) {  
  14.         Connection conn = null;  
  15.         String url = "jdbc:mysql://localhost:3306/ptest";  
  16.         String jdbcDriver = "com.mysql.jdbc.Driver";  
  17.         String user = "root";  
  18.         String password = "ptest";  
  19.   
  20.         DbUtils.loadDriver(jdbcDriver);  
  21.         //****************************转换成list  ************************************  
  22.         try {  
  23.             conn = DriverManager.getConnection(url, user, password);  
  24.             QueryRunner qr = new QueryRunner();  
  25.             List results = (List) qr.query(conn, "select id,name from person",new BeanListHandler(Person.class));  
  26.             for (int i = 0; i < results.size(); i++) {  
  27.                 Person p = (Person) results.get(i);  
  28.                 System.out.println("age:" + p.getAge() + ",name:" + p.getName());  
  29.             }  
  30.         } catch (SQLException e) {  
  31.             e.printStackTrace();  
  32.         } finally {  
  33.             DbUtils.closeQuietly(conn);  
  34.         }  
  35.         //****************************转换成map  ************************************  
  36.         try {  
  37.             conn = DriverManager.getConnection(url, user, password);  
  38.             QueryRunner qr = new QueryRunner();  
  39.             List results = (List) qr.query(conn, "select age,name from person",new MapListHandler());  
  40.             for (int i = 0; i < results.size(); i++) {  
  41.                 Map map = (Map) results.get(i);  
  42.                 System.out.println("age:" + map.get("age") + ",name:"+ map.get("name"));  
  43.             }  
  44.         } catch (SQLException e) {  
  45.             e.printStackTrace();  
  46.         } finally {  
  47.             DbUtils.closeQuietly(conn);  
  48.         }  
  49.     }  
  50. }  
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

public class CommonsDbutils {

	public static void main(String[] args) {
		Connection conn = null;
		String url = "jdbc:mysql://localhost:3306/ptest";
		String jdbcDriver = "com.mysql.jdbc.Driver";
		String user = "root";
		String password = "ptest";

		DbUtils.loadDriver(jdbcDriver);
		//****************************转换成list  ************************************
		try {
			conn = DriverManager.getConnection(url, user, password);
			QueryRunner qr = new QueryRunner();
			List results = (List) qr.query(conn, "select id,name from person",new BeanListHandler(Person.class));
			for (int i = 0; i < results.size(); i++) {
				Person p = (Person) results.get(i);
				System.out.println("age:" + p.getAge() + ",name:" + p.getName());
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}
		//****************************转换成map  ************************************
		try {
			conn = DriverManager.getConnection(url, user, password);
			QueryRunner qr = new QueryRunner();
			List results = (List) qr.query(conn, "select age,name from person",new MapListHandler());
			for (int i = 0; i < results.size(); i++) {
				Map map = (Map) results.get(i);
				System.out.println("age:" + map.get("age") + ",name:"+ map.get("name"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}
	}
}

9、commons-email 

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

 

Java代码   收藏代码
  1. import org.apache.commons.mail.DefaultAuthenticator;  
  2. import org.apache.commons.mail.Email;  
  3. import org.apache.commons.mail.EmailException;  
  4. import org.apache.commons.mail.SimpleEmail;  
  5.   
  6. public class CommosEmail {  
  7.     public static void main(String[] args) throws EmailException {  
  8.         Email email = new SimpleEmail();  
  9.         email.setHostName("smtp.googlemail.com");  
  10.         email.setSmtpPort(465);  
  11.         email.setAuthenticator(new DefaultAuthenticator("username""password"));  
  12.         email.setSSLOnConnect(true);  
  13.         email.setFrom("user@gmail.com");  
  14.         email.setSubject("TestMail");  
  15.         email.setMsg("This is a test mail ... :-)");  
  16.         email.addTo("foo@bar.com");  
  17.         email.send();  
  18.     }  
  19. }  
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

public class CommosEmail {
	public static void main(String[] args) throws EmailException {
		Email email = new SimpleEmail();
		email.setHostName("smtp.googlemail.com");
		email.setSmtpPort(465);
		email.setAuthenticator(new DefaultAuthenticator("username", "password"));
		email.setSSLOnConnect(true);
		email.setFrom("user@gmail.com");
		email.setSubject("TestMail");
		email.setMsg("This is a test mail ... :-)");
		email.addTo("foo@bar.com");
		email.send();
	}
}

10、commons-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、commons-httpclient

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

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

public class CommonsHttpclient {
	public static void main(String[] args) {
		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		// 创建GET方法的实例
		GetMethod getMethod = new GetMethod("http://www.ibm.com");
		// 使用系统提供的默认的恢复策略
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());
		try {
			// 执行getMethod
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: "
						+ getMethod.getStatusLine());
			}
			// 读取内容
			byte[] responseBody = getMethod.getResponseBody();
			// 处理内容
			System.out.println(new String(responseBody));
		} catch (HttpException e) {
			// 发生致命的异常,可能是协议不对或者返回的内容有问题
			System.out.println("Please check your provided http address!");
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			e.printStackTrace();
		} finally {
			// 释放连接
			getMethod.releaseConnection();
		}

		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		// 创建POST方法的实例
		String url = "http://www.oracle.com/";
		PostMethod postMethod = new PostMethod(url);
		// 填入各个表单域的值
		NameValuePair[] data = { new NameValuePair("id", "youUserName"),
				new NameValuePair("passwd", "yourPwd") };
		// 将表单的值放入postMethod中
		postMethod.setRequestBody(data);
		// 执行postMethod
		int statusCode = httpClient.executeMethod(postMethod);
		// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
		// 301或者302
		if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
				|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
			// 从头中取出转向的地址
			Header locationHeader = postMethod.getResponseHeader("location");
			String location = null;
			if (locationHeader != null) {
				location = locationHeader.getValue();
				System.out.println("The page was redirected to:" + location);
			} else {
				System.err.println("Location field value is null.");
			}
			return;
		}
	}
}

12、commons-io

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

 

Java代码   收藏代码
  1. import java.io.BufferedReader;  
  2. import java.io.File;  
  3. import java.io.InputStream;  
  4. import java.io.InputStreamReader;  
  5. import java.net.URL;  
  6. import java.util.List;  
  7.   
  8. import org.apache.commons.io.FileSystemUtils;  
  9. import org.apache.commons.io.FileUtils;  
  10. import org.apache.commons.io.IOUtils;  
  11.   
  12. public class CommonsIo {  
  13.     public static void main(String[] args) throws Exception {  
  14.         // 1.读取Stream  
  15.         // 标准代码:  
  16.         InputStream in = new URL("http://jakarta.apache.org").openStream();  
  17.         InputStreamReader inR = new InputStreamReader(in);  
  18.         BufferedReader buf = new BufferedReader(inR);  
  19.         String line;  
  20.         while ((line = buf.readLine()) != null) {  
  21.             System.out.println(line);  
  22.         }  
  23.         in.close();  
  24.           
  25.         // 使用IOUtils  
  26.         InputStream in2 = new URL("http://jakarta.apache.org").openStream();  
  27.         try {  
  28.             System.out.println(IOUtils.toString(in2));  
  29.         } finally {  
  30.             IOUtils.closeQuietly(in);  
  31.         }  
  32.   
  33.         // 2.读取文件  
  34.         File file = new File("/commons/io/project.properties");  
  35.         List lines = FileUtils.readLines(file, "UTF-8");  
  36.   
  37.         // 3.察看剩余空间  
  38.         long freeSpace = FileSystemUtils.freeSpace("C:/");  
  39.     }  
  40. }  
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;

import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class CommonsIo {
	public static void main(String[] args) throws Exception {
		// 1.读取Stream
		// 标准代码:
		InputStream in = new URL("http://jakarta.apache.org").openStream();
		InputStreamReader inR = new InputStreamReader(in);
		BufferedReader buf = new BufferedReader(inR);
		String line;
		while ((line = buf.readLine()) != null) {
			System.out.println(line);
		}
		in.close();
		
		// 使用IOUtils
		InputStream in2 = new URL("http://jakarta.apache.org").openStream();
		try {
			System.out.println(IOUtils.toString(in2));
		} finally {
			IOUtils.closeQuietly(in);
		}

		// 2.读取文件
		File file = new File("/commons/io/project.properties");
		List lines = FileUtils.readLines(file, "UTF-8");

		// 3.察看剩余空间
		long freeSpace = FileSystemUtils.freeSpace("C:/");
	}
}

13、commos-lang 

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

Java代码   收藏代码
  1. import java.util.Calendar;  
  2. import java.util.Date;  
  3.   
  4. import org.apache.commons.lang.ArrayUtils;  
  5. import org.apache.commons.lang.ClassUtils;  
  6. import org.apache.commons.lang.RandomStringUtils;  
  7. import org.apache.commons.lang.StringEscapeUtils;  
  8. import org.apache.commons.lang.StringUtils;  
  9. import org.apache.commons.lang.time.DateFormatUtils;  
  10. import org.apache.commons.lang.time.DateUtils;  
  11.   
  12. public class CommonsLang {  
  13.     public static void main(String[] args) throws Exception {  
  14.         //********************************ArrayUtils***************************************  
  15.         // 将两个数组合并为一个数组  
  16.         String[] s1 = new String[] { "1""2""3" };  
  17.         String[] s2 = new String[] { "a""b""c" };  
  18.         String[] s = (String[]) ArrayUtils.addAll(s1, s2);  
  19.         for (int i = 0; i < s.length; i++) {  
  20.             System.out.println(s[i]);  
  21.         }  
  22.         String str = ArrayUtils.toString(s);  
  23.         str = str.substring(1, str.length() - 1);  
  24.         System.out.println(str + ">>" + str.length());  
  25.         //********************************StringUtils***************************************  
  26.         // 截取从from开始字符串  
  27.         StringUtils.substringAfter("SELECT * FROM PERSON ""from");  
  28.         // 判断该字符串是不是为数字(0~9)组成,如果是,返回true 但该方法不识别有小数点和请注意  
  29.         StringUtils.isNumeric("454534"); // 返回true  
  30.         // 取得类名  
  31.         System.out.println(ClassUtils.getShortClassName(CommonsLang.class));  
  32.         // 取得其包名  
  33.         System.out.println(ClassUtils.getPackageName(CommonsLang.class));  
  34.         // 五位的随机字母和数字   
  35.         System.out.println(RandomStringUtils.randomAlphanumeric(5));  
  36.         // StringEscapeUtils  
  37.         System.out.println(StringEscapeUtils.escapeHtml("<html>"));  
  38.         // 输出结果为<html>  
  39.         System.out.println(StringEscapeUtils.escapeJava("String"));  
  40.         // StringUtils,判断是否是空格字符  
  41.         System.out.println(StringUtils.isBlank("   "));  
  42.         // 将数组中的内容以,分隔  
  43.         System.out.println(StringUtils.join(s1, ","));  
  44.         // 在右边加下字符,使之总长度为6  
  45.         System.out.println(StringUtils.rightPad("abc"6'T'));  
  46.         // 首字母大写   
  47.         System.out.println(StringUtils.capitalize("abc"));  
  48.         // Deletes all whitespaces from a String 删除所有空格  
  49.         System.out.println(StringUtils.deleteWhitespace("   ab  c  "));  
  50.         // 判断是否包含这个字符   
  51.         System.out.println(StringUtils.contains("abc""ba"));  
  52.         // 表示左边两个字符   
  53.         System.out.println(StringUtils.left("abc"2));  
  54.         //********************************DateFormatUtils***************************************  
  55.         System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));  
  56.         //直接将日期格式化为内置的固定格式  
  57.         System.out.println(DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));  
  58.         //字符型日期转化为Date  
  59.         System.out.println(DateUtils.parseDate("2014-11-11 11:11:11"new String[] { "yyyy-MM-dd HH:mm:ss""yyyy-MM-dd HH:mm""yyyy-MM-dd""yyyy/MM/dd" }));  
  60.         //日期舍入与截整  
  61.         System.out.println(DateUtils.truncate(new Date(), Calendar.DATE));  
  62.         //判断是否是同一天  
  63.         System.out.println(DateUtils.isSameDay(new Date(), new Date()));  
  64.         //加天数  
  65.         System.out.println(DateUtils.addDays(new Date(), 10));  
  66.     }  
  67. }  
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.ClassUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;

public class CommonsLang {
	public static void main(String[] args) throws Exception {
		//********************************ArrayUtils***************************************
		// 将两个数组合并为一个数组
		String[] s1 = new String[] { "1", "2", "3" };
		String[] s2 = new String[] { "a", "b", "c" };
		String[] s = (String[]) ArrayUtils.addAll(s1, s2);
		for (int i = 0; i < s.length; i++) {
			System.out.println(s[i]);
		}
		String str = ArrayUtils.toString(s);
		str = str.substring(1, str.length() - 1);
		System.out.println(str + ">>" + str.length());
		//********************************StringUtils***************************************
		// 截取从from开始字符串
		StringUtils.substringAfter("SELECT * FROM PERSON ", "from");
		// 判断该字符串是不是为数字(0~9)组成,如果是,返回true 但该方法不识别有小数点和请注意
		StringUtils.isNumeric("454534"); // 返回true
		// 取得类名
		System.out.println(ClassUtils.getShortClassName(CommonsLang.class));
		// 取得其包名
		System.out.println(ClassUtils.getPackageName(CommonsLang.class));
		// 五位的随机字母和数字 
		System.out.println(RandomStringUtils.randomAlphanumeric(5));
		// StringEscapeUtils
		System.out.println(StringEscapeUtils.escapeHtml("<html>"));
		// 输出结果为<html>
		System.out.println(StringEscapeUtils.escapeJava("String"));
		// StringUtils,判断是否是空格字符
		System.out.println(StringUtils.isBlank("   "));
		// 将数组中的内容以,分隔
		System.out.println(StringUtils.join(s1, ","));
		// 在右边加下字符,使之总长度为6
		System.out.println(StringUtils.rightPad("abc", 6, 'T'));
		// 首字母大写 
		System.out.println(StringUtils.capitalize("abc"));
		// Deletes all whitespaces from a String 删除所有空格
		System.out.println(StringUtils.deleteWhitespace("   ab  c  "));
		// 判断是否包含这个字符 
		System.out.println(StringUtils.contains("abc", "ba"));
		// 表示左边两个字符 
		System.out.println(StringUtils.left("abc", 2));
		//********************************DateFormatUtils***************************************
		System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		//直接将日期格式化为内置的固定格式
		System.out.println(DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));
		//字符型日期转化为Date
		System.out.println(DateUtils.parseDate("2014-11-11 11:11:11", new String[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "yyyy/MM/dd" }));
		//日期舍入与截整
		System.out.println(DateUtils.truncate(new Date(), Calendar.DATE));
		//判断是否是同一天
		System.out.println(DateUtils.isSameDay(new Date(), new Date()));
		//加天数
		System.out.println(DateUtils.addDays(new Date(), 10));
	}
}


14、commos-logging

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

 

Java代码   收藏代码
  1. import org.apache.commons.logging.Log;  
  2. import org.apache.commons.logging.LogFactory;  
  3.   
  4. public class CommosLogging {  
  5.     private static Log log = LogFactory.getLog(CommosLogging.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. }  
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CommosLogging {
	private static Log log = LogFactory.getLog(CommosLogging.class);

	public static void main(String[] args) {
		log.error("ERROR");
		log.debug("DEBUG");
		log.warn("WARN");
		log.info("INFO");
		log.trace("TRACE");
		System.out.println(log.getClass());
	}
}


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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值