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代码 
- 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");
-
- Person person3 = new Person();
- BeanUtils.populate(person3, map);
- System.out.println(person3.getName() + ">>" + person3.getAge());
-
-
- Map<String, String> map2 = BeanUtils.describe(person3);
- System.out.println(map2.get("name") + ">>" + map2.get("age"));
-
- Person person4 = new Person();
- person4.setName("andy");
-
- String name = (String) PropertyUtils.getProperty(person4, "name");
- System.out.println(name);
-
- PropertyUtils.setProperty(person4, "age", 25);
- System.out.println(person4.getAge());
- }
- }
- 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");
-
- Person person3 = new Person();
- BeanUtils.populate(person3, map);
- System.out.println(person3.getName() + ">>" + person3.getAge());
-
-
- Map<String, String> map2 = BeanUtils.describe(person3);
- System.out.println(map2.get("name") + ">>" + map2.get("age"));
-
- Person person4 = new Person();
- person4.setName("andy");
-
- String name = (String) PropertyUtils.getProperty(person4, "name");
- System.out.println(name);
-
- PropertyUtils.setProperty(person4, "age", 25);
- System.out.println(person4.getAge());
- }
- }
2、commons-betwixt
XML与Java对象之间相互转换。
Java代码

- 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 {
-
-
- StringWriter outputWriter = new StringWriter();
-
-
- outputWriter.write("<?xml version=’1.0′ encoding=’UTF-8′ ?>\n");
-
- BeanWriter beanWriter = new BeanWriter(outputWriter);
-
-
- beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
- beanWriter.getBindingConfiguration().setMapIDs(false);
- beanWriter.enablePrettyPrint();
-
-
- beanWriter.write("person", new Person("John Smith", 21));
-
- System.out.println(outputWriter.toString());
-
-
- outputWriter.close();
-
-
- StringReader xmlReader = new StringReader("<?xml version='1.0' encoding='UTF-8' ?> <person><age>25</age><name>James Smith</name></person>");
-
- BeanReader beanReader = new BeanReader();
-
- beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
- beanReader.getBindingConfiguration().setMapIDs(false);
-
- beanReader.registerBeanClass("person", Person.class);
-
- Person person = (Person) beanReader.parse(xmlReader);
-
- System.out.println(person);
- }
- }
- 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 {
-
-
- StringWriter outputWriter = new StringWriter();
-
-
- outputWriter.write("<?xml version=’1.0′ encoding=’UTF-8′ ?>\n");
-
- BeanWriter beanWriter = new BeanWriter(outputWriter);
-
-
- beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
- beanWriter.getBindingConfiguration().setMapIDs(false);
- beanWriter.enablePrettyPrint();
-
-
- beanWriter.write("person", new Person("John Smith", 21));
-
- System.out.println(outputWriter.toString());
-
-
- outputWriter.close();
-
-
- StringReader xmlReader = new StringReader("<?xml version='1.0' encoding='UTF-8' ?> <person><age>25</age><name>James Smith</name></person>");
-
- BeanReader beanReader = new BeanReader();
-
- beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
- beanReader.getBindingConfiguration().setMapIDs(false);
-
- beanReader.registerBeanClass("person", Person.class);
-
- Person person = (Person) beanReader.parse(xmlReader);
-
- System.out.println(person);
- }
- }
3、commons-codec
提供了一些公共的编解码实现,比如Base64, Hex, MD5,Phonetic and URLs等等。
Java代码

- 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);
- }
- }
- 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代码

- 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) {
-
- OrderedMap map = new LinkedMap ();
- map.put("FIVE", "5");
- map.put("SIX", "6");
- map.put("SEVEN", "7");
- map.firstKey();
- map.nextKey("FIVE");
- map.nextKey("SIX");
-
-
- BidiMap bidi = new TreeBidiMap();
- bidi.put("SIX", "6");
- bidi.get("SIX");
- bidi.getKey("6");
-
- BidiMap inverse = bidi.inverseBidiMap();
- 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);
- }
- }
- 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) {
-
- OrderedMap map = new LinkedMap ();
- map.put("FIVE", "5");
- map.put("SIX", "6");
- map.put("SEVEN", "7");
- map.firstKey();
- map.nextKey("FIVE");
- map.nextKey("SIX");
-
-
- BidiMap bidi = new TreeBidiMap();
- bidi.put("SIX", "6");
- bidi.get("SIX");
- bidi.getKey("6");
-
- BidiMap inverse = bidi.inverseBidiMap();
- 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代码

- 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();
- }
- }
- 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代码

- //举一个Properties的简单例子
- # usergui.properties
- colors.background = #FFFFFF
- colors.foreground = #000080
- window.width = 500
- window.height = 300
-
- PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");
- config.setProperty("colors.background", "#000000);
- config.save();
-
- config.save("usergui.backup.properties);//save a copy
- Integer integer = config.getInteger("window.width");
7、commons-dbcp
(Database Connection Pool)是一个依赖Jakarta commons-pool对象池机制的数据库连接池,Tomcat的数据源使用的就是DBCP。
Java代码

- 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);
-
-
- ObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory);
-
-
- PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
-
- return dataSource;
- }
- }
- 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);
-
-
- ObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory);
-
-
- 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代码

- 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);
-
- 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);
- }
-
- 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);
- }
- }
- }
- 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);
-
- 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);
- }
-
- 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代码

- 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();
- }
- }
- 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代码

- //官方示例:
- //* 检查请求是否含有上传文件
- // Check that we have a file upload request
- boolean isMultipart = ServletFileUpload.isMultipartContent(request);
-
- //现在我们得到了items的列表
-
- //如果你的应用近于最简单的情况,上面的处理就够了。但我们有时候还是需要更多的控制。
- //下面提供了几种控制选择:
- // Create a factory for disk-based file items
- DiskFileItemFactory factory = new DiskFileItemFactory();
-
- // Set factory constraints
- factory.setSizeThreshold(yourMaxMemorySize);
- factory.setRepository(yourTempDirectory);
-
- // Create a new file upload handler
- ServletFileUpload upload = new ServletFileUpload(factory);
-
- // 设置最大上传大小
- upload.setSizeMax(yourMaxRequestSize);
-
- // 解析所有请求
- List /* FileItem */ items = upload.parseRequest(request);
-
- // Create a factory for disk-based file items
- DiskFileItemFactory factory = new DiskFileItemFactory(
- yourMaxMemorySize, yourTempDirectory);
-
- //一旦解析完成,你需要进一步处理item的列表。
- // Process the uploaded items
- Iterator iter = items.iterator();
- while (iter.hasNext()) {
- FileItem item = (FileItem) iter.next();
-
- if (item.isFormField()) {
- processFormField(item);
- } else {
- processUploadedFile(item);
- }
- }
-
- //区分数据是否为简单的表单数据,如果是简单的数据:
- // processFormField
- if (item.isFormField()) {
- String name = item.getFieldName();
- String value = item.getString();
- //...省略步骤
- }
-
- //如果是提交的文件:
- // processUploadedFile
- if (!item.isFormField()) {
- String fieldName = item.getFieldName();
- String fileName = item.getName();
- String contentType = item.getContentType();
- boolean isInMemory = item.isInMemory();
- long sizeInBytes = item.getSize();
- //...省略步骤
- }
-
- //对于这些item,我们通常要把它们写入文件,或转为一个流
- // Process a file upload
- if (writeToFile) {
- File uploadedFile = new File(...);
- item.write(uploadedFile);
- } else {
- InputStream uploadedStream = item.getInputStream();
- //...省略步骤
- uploadedStream.close();
- }
-
- //或转为字节数组保存在内存中:
- // Process a file upload in memory
- byte[] data = item.get();
- //...省略步骤
- //如果这个文件真的很大,你可能会希望向用户报告到底传了多少到服务端,让用户了解上传的过程
- //Create a progress listener
- ProgressListener progressListener = new ProgressListener(){
- public void update(long pBytesRead, long pContentLength, int pItems) {
- System.out.println("We are currently reading item " + pItems);
- if (pContentLength == -1) {
- System.out.println("So far, " + pBytesRead + " bytes have been read.");
- } else {
- System.out.println("So far, " + pBytesRead + " of " + pContentLength
- + " bytes have been read.");
- }
- }
- };
- upload.setProgressListener(progressListener);
11、commons-httpclient
基于HttpCore实 现的一个HTTP/1.1兼容的HTTP客户端,它提供了一系列可重用的客户端身份验证、HTTP状态保持、HTTP连接管理module。
Java代码

- 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 = new HttpClient();
-
- GetMethod getMethod = new GetMethod("http://www.ibm.com");
-
- getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
- new DefaultHttpMethodRetryHandler());
- try {
-
- 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 = new HttpClient();
-
- String url = "http://www.oracle.com/";
- PostMethod postMethod = new PostMethod(url);
-
- NameValuePair[] data = { new NameValuePair("id", "youUserName"),
- new NameValuePair("passwd", "yourPwd") };
-
- postMethod.setRequestBody(data);
-
- int statusCode = httpClient.executeMethod(postMethod);
-
-
- 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;
- }
- }
- }
- 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 = new HttpClient();
-
- GetMethod getMethod = new GetMethod("http://www.ibm.com");
-
- getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
- new DefaultHttpMethodRetryHandler());
- try {
-
- 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 = new HttpClient();
-
- String url = "http://www.oracle.com/";
- PostMethod postMethod = new PostMethod(url);
-
- NameValuePair[] data = { new NameValuePair("id", "youUserName"),
- new NameValuePair("passwd", "yourPwd") };
-
- postMethod.setRequestBody(data);
-
- int statusCode = httpClient.executeMethod(postMethod);
-
-
- 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代码

- 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 {
-
-
- 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();
-
-
- InputStream in2 = new URL("http://jakarta.apache.org").openStream();
- try {
- System.out.println(IOUtils.toString(in2));
- } finally {
- IOUtils.closeQuietly(in);
- }
-
-
- File file = new File("/commons/io/project.properties");
- List lines = FileUtils.readLines(file, "UTF-8");
-
-
- long freeSpace = FileSystemUtils.freeSpace("C:/");
- }
- }
- 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 {
-
-
- 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();
-
-
- InputStream in2 = new URL("http://jakarta.apache.org").openStream();
- try {
- System.out.println(IOUtils.toString(in2));
- } finally {
- IOUtils.closeQuietly(in);
- }
-
-
- File file = new File("/commons/io/project.properties");
- List lines = FileUtils.readLines(file, "UTF-8");
-
-
- long freeSpace = FileSystemUtils.freeSpace("C:/");
- }
- }
13、commos-lang
主要是一些公共的工具集合,比如对字符、数组的操作等等。

Java代码

- 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 {
-
-
- 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.substringAfter("SELECT * FROM PERSON ", "from");
-
- StringUtils.isNumeric("454534");
-
- System.out.println(ClassUtils.getShortClassName(CommonsLang.class));
-
- System.out.println(ClassUtils.getPackageName(CommonsLang.class));
-
- System.out.println(RandomStringUtils.randomAlphanumeric(5));
-
- System.out.println(StringEscapeUtils.escapeHtml("<html>"));
-
- System.out.println(StringEscapeUtils.escapeJava("String"));
-
- System.out.println(StringUtils.isBlank(" "));
-
- System.out.println(StringUtils.join(s1, ","));
-
- System.out.println(StringUtils.rightPad("abc", 6, 'T'));
-
- System.out.println(StringUtils.capitalize("abc"));
-
- System.out.println(StringUtils.deleteWhitespace(" ab c "));
-
- System.out.println(StringUtils.contains("abc", "ba"));
-
- System.out.println(StringUtils.left("abc", 2));
-
- System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
-
- System.out.println(DateFormatUtils.ISO_DATE_FORMAT.format(new 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));
- }
- }
- 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 {
-
-
- 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.substringAfter("SELECT * FROM PERSON ", "from");
-
- StringUtils.isNumeric("454534");
-
- System.out.println(ClassUtils.getShortClassName(CommonsLang.class));
-
- System.out.println(ClassUtils.getPackageName(CommonsLang.class));
-
- System.out.println(RandomStringUtils.randomAlphanumeric(5));
-
- System.out.println(StringEscapeUtils.escapeHtml("<html>"));
-
- System.out.println(StringEscapeUtils.escapeJava("String"));
-
- System.out.println(StringUtils.isBlank(" "));
-
- System.out.println(StringUtils.join(s1, ","));
-
- System.out.println(StringUtils.rightPad("abc", 6, 'T'));
-
- System.out.println(StringUtils.capitalize("abc"));
-
- System.out.println(StringUtils.deleteWhitespace(" ab c "));
-
- System.out.println(StringUtils.contains("abc", "ba"));
-
- System.out.println(StringUtils.left("abc", 2));
-
- System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
-
- System.out.println(DateFormatUtils.ISO_DATE_FORMAT.format(new 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代码

- 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());
- }
- }
- 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代码

- // 获取日期验证
- DateValidator validator = DateValidator.getInstance();
-
- // 验证/转换日期
- Date fooDate = validator.validate(fooString, "dd/MM/yyyy");
- if (fooDate == null) {
- // 错误 不是日期
- return;
- }
表达式验证
Java代码

- // 设置参数
- boolean caseSensitive = false;
- String regex1 = "^([A-Z]*)(?:\\-)([A-Z]*)*$"
- String regex2 = "^([A-Z]*)$";
- String[] regexs = new String[] {regex1, regex1};
-
- // 创建验证
- RegexValidator validator = new RegexValidator(regexs, caseSensitive);
-
- // 验证返回boolean
- boolean valid = validator.isValid("abc-def");
-
- // 验证返回字符串
- String result = validator.validate("abc-def");
-
- // 验证返回数组
- String[] groups = validator.match("abc-def");
配置文件中使用验证
Xml代码

- <form-validation>
- <global>
- <validator name="required"
- classname="org.apache.commons.validator.TestValidator"
- method="validateRequired"
- methodParams="java.lang.Object, org.apache.commons.validator.Field"/>
- </global>
- <formset>
- </formset>
- </form-validation>
-
- 添加姓名验证.
-
- <form-validation>
- <global>
- <validator name="required"
- classname="org.apache.commons.validator.TestValidator"
- method="validateRequired"
- methodParams="java.lang.Object, org.apache.commons.validator.Field"/>
- </global>
- <formset>
- <form name="nameForm">
- <field property="firstName" depends="required">
- <arg0 key="nameForm.firstname.displayname"/>
- </field>
- <field property="lastName" depends="required">
- <arg0 key="nameForm.lastname.displayname"/>
- </field>
- </form>
- </formset>
- </form-validation>
验证类
Java代码

- Excerpts from org.apache.commons.validator.RequiredNameTest
- //加载验证配置文件
- InputStream in = this.getClass().getResourceAsStream("validator-name-required.xml");
-
- ValidatorResources resources = new ValidatorResources(in);
- //这个是自己创建的bean 我这里省略了
- Name name = new Name();
-
- Validator validator = new Validator(resources, "nameForm");
- //设置参数
- validator.setParameter(Validator.BEAN_PARAM, name);
-
-
- Map results = null;
- //验证
- results = validator.validate();
-
- if (results.get("firstName") == null) {
- //验证成功
- } else {
- //有错误 int errors = ((Integer)results.get("firstName")).intValue();
- }
转载自:http://blog.csdn.net/chx10051413/article/details/42059413