Apache Commonsには、プログラミングでしばしば遭遇する問題を解決し、繰り返し労働を減らすための多くのオープンソースツールが含まれています。以下は、過去数年間の開発プロセス中に使用したツールの簡単な紹介です。
| コンポーネント | 機能的な紹介 |
| beanutils | Javabeansには、さまざまな操作、クローニングオブジェクト、プロパティなどを提供します。 |
| betwixt | XMLとJavaオブジェクトを互いに変換します。 |
| コーデック | DES、SHA1、MD5、Base64などの一般的に使用されるコーディング方法を扱うツール。 |
| コレクション | Javaコレクションフレームワーク操作。 |
| 圧縮 | Javaは、ファイルパッケージ圧縮クラスライブラリを提供します。 |
| 構成 | Javaアプリケーション用の構成管理クラスライブラリ。 |
| DBCP | データベース接続プーリングサービスを提供します。 |
| dbutils | JDBCの操作カプセル化を提供して、データクエリを簡素化し、読み取り操作を記録します。 |
| メール | JavaはJavamailのカプセル化にメールを送信します。 |
| fileupload | ファイルアップロード機能を提供します。 |
| httpclient | HTTPクライアントとサーバー間のさまざまな通信操作を提供します。現在、httpComponentsに変更されています |
| io | IOツールのカプセル化。 |
| ラング | Stringutils、ArrayutilsなどのJava基本オブジェクトメソッド用のツールクラスパッケージ。 |
| ロギング | Javaロギングインターフェイスを提供します。 |
| バリデーター | クライアント側とサーバー側のデータ検証フレームワークを提供します。 |
1。Beanutilsは、オブジェクト、属性コピーなど、Javabeansにさまざまな操作を提供します。
// 1。クローンオブジェクト//クローン化されたオブジェクトとして使用される新しい通常のJava Beanを作成するパブリッククラスの人{private string name = ""; private string email = ""; private int age; // omit set} //メインメソッドのコードが次のとおりです。 java.util.map; Import org.apache.commons.beanutils.beanutils; import org.apache.commons.beanutils.convertutils; public class test {/** * @param args */public static void main(string [] args){iners person = new person(21); setname(); setname {// clone person2 =(person)beanutils.clonebean(person); system.out.println(person2.getname()+">"> "+person2.getage();} catch(Illegalaccessexception e){e.printstacktrace();} catch(instantivationexception ex(e.printstacktrace(); e){e.printstacktrace();} catch(nosuchmethodexception e){e.printstacktrace();}}} //原理は、Java反射メカニズムによっても行われます。 // 2。マップオブジェクトを豆に変換する//このマップオブジェクトのキーは、Beanのプロパティに対応する必要があります。 Map Map = new Hashmap(); Map.put( "name"、 "tom"); map.put( "email"、 "tom@"); map.put( "age"、 "21"); //マップを人物の人に変換する人= new人(); beanutils.populate(); //次のように、豆をマップオブジェクトに変換します:マップマップ= beanutils.describe(人)2。BetWixtXMLおよびJavaオブジェクトが変換されます。
// 1。 JavabeanをXMLコンテンツに変換//新しい人クラスのパブリッククラスの人を作成します{private string name; private int age;/**反射*/public personbean(){} public personbean(){} public name(string name、int age){this.name = name; this.age = age;} "'、age ='" + age + "']";}} // writeappクラスを作成:java.io.stringwriterをインポート; inmolg.apache.commons.betwixt.io.beanwriter; public class writeapp {/*** beanの例を作成し、xmlに変換します。 */public static final void main(string [] args)throws exception {//最初にstringwriter outputwriter = new stringwriter(); // betwixtはbeanをフラグメントとして書きます。 encoding = 'utf-8'?>/n "); // BeanWriterを作成します。これは、準備したストリームに書き込まれます。 BeanWriter BeanWriter = new BeanWriter(outputWriter); // configure betwixt //詳細については、Javaドキュメントまたは最新のドキュメントを参照してくださいbeanWriter.getXmlintrospector()。getConfiguration()。setattributesforprimitives(false); beanWriter.getBindingConfiguration()。setMapids()。setMapids(false); beanWriter.enable prettyprint(); // root node beanwriter.write( "person"、new Personbean( "John Smith"、21)); // output result System.out.println(outputwriter.tostring()); // betwixtはドキュメントではなくフラグメントを書きます。 outputwriter.close();}} // 2。 XMLをjavabeanに変換しますjava.io.stringreader; import org.apache.commons.betwixt.io.beanreader; public class readapp {public static final void main(string args [])throws exception {// xmlを最初に作成します。これは単なる例であるため、XMLコンテンツストリングリーダーXMLReader = new StringReader( "<?xmlバージョン= '1.0'エンコード= 'utf-8'?> <serson> <age> 25 </age> <age> <age> <name> james smith </name> </person>"); beanreader.getXmlintrospector()。getConfiguration()。setattributesforprimitives(false); beanreader.getbindingConfiguration()。setmapids(false); // register bean PersonBean Person =(PersonBean)BeanReader.Parse(XMLReader); //出力結果System.out.println(person);}}}3. Codecは、Base64、HEX、MD5、Phonetic、URLSなどのパブリックコーデックの実装を提供します。
// base64 Codec Private Static String encodetest(String str){base64 base64 = new base64(); try {str = base64.encodetostring( "utf-8");} catch(unsupportedencodingexception e){e.printstrace(e.printstrace(); "+str); return str;} private static void decodetest(string str){base64 base64 = new base64(); // str = arrays.toString(base64.decodebase64(str)); str = new String(base64.decodebase64(str)); System.out.println( "base64デコード:"+str);}4.コレクションはjava.utilを拡張し、プロセスデータを非常に柔軟に拡張します。
org.apache.commons.collectionsコモンズコレクションカスタマイズされた共通インターフェイスとツールクラスのセット
org.apache.commons.collections.bagバッグインターフェイスを実装する一連のクラス
org.apache.commons.collections.bidimap bidimapシリーズインターフェイスを実装する一連のクラス
org.apache.commons.collections.bufferバッファインターフェイスを実装する一連のクラス
org.apache.commons.collections.collection java.util.collectionインターフェイスを実装する一連のクラス
org.apache.commons.collections.comparators java.util.comparatorインターフェイスを実装する一連のクラス
org.apache.commons.collections.functors commonsコレクションカスタマイズされた機能クラスのセット
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マップシリーズインターフェイスを実装する一連のクラス
org.apache.commons.collections.set setシリーズインターフェイスを実装するクラスのセット
/** *セットに保存されたキーの後に特定のキーを取得 */orderedMap Map = new LinkedMap(); Map.put( "Five"、 "5"); map.put( "6"、 "6"); map.put( "7"、 "7"); map.firstkey(); // "vive map.next"); 「7」を返す/** *キーを介して値を取得する * value * switchキーとマップのキーと値を取得 */bidimap bidi = new treebidimap(); bidi.put( "6"、 "6"); bidi.get( "6"); // returns "6" bidi.getkey( "6"); // returns "// bidi.removevalue(" 6 "); //マッピングを削除するbidimap inverse = bidi.inversebidimap(); //キーと値をスワップしたsystem.out.println(inverse);/*** 2つのセットで同じ要素を取得します*/list <string> list1 = newで同じ要素を取得しますArrayList <String>(); list1.add( "1"); list1.add( "2"); list1.add( "3"); list <string> list2 = new arraylist <string>( "2"); list2.add( "3"); list2.add( "5"); list2); system.out.println(c);
5.パッケージ化されたコンプレッドクラスライブラリを圧縮します。
//圧縮オブジェクトの作成ZiparchiveEntryエントリ= new ZiparchiveEntry( "Compresstest"); //圧縮されるファイルf = new file( "e://test.pdf"); fileinputStream fis = new fileinputStream(f); file( "e://test.zip")); zipoutput.putarchiveentry(entry); int i = 0、j; while(j = fis.read())
6.構成は、構成ファイルの処理を支援し、多くのストレージ方法をサポートするために使用されます。
1。プロパティファイル
2。XMLドキュメント
3。プロパティリストファイル(.plist)
4。Jndi
5。JDBCDataSource
6。システムプロパティ
7。アプレットパラメーター
8。サーブレットパラメーター
//プロパティの簡単な例を挙げてくださいconfig.save( "usergui.backup.properties); // integer integer = config.getinteger(" window.width ");
7。DBCP(データベース接続プール)は、Jakarta Commons-Poolオブジェクトプールメカニズムに依存するデータベース接続プールです。 TomcatのデータソースはDBCPを使用しています。
javax.sql.datasource; Import java.sql.connection; import java.sql.statement; import java.sql.Resultset; Import java.sql.sqlexception; import org.apache.commons.pool.pool.objectpool; import org.commons.commons.commons.pool.pool.pool.pool.pool.pool org.apache.commons.dbcp.ConnectionFactory;import org.apache.commons.dbcp.PoolingDataSource;import org.apache.commons.dbcp.PoolableConnectionFactory;import org.apache.commons.dbcp.DriverManagerConnectionFactory;//Official Example public class PoolingDataSources {public static void main(string [] args){system.out.println( "load jdbc driver"); try {class.forname( "oracle.jdbc.driver.oracledriver");} catch(classNotFoundException e){e.printstacktrace();} system.out.out.out.out.Outln( ");ソース "); DataSource DataSource = setUpDataSource(" JDBC:Oracle:Thin:@LocalHost:1521:test "); system.out.println(" done "); // connection conn = null; statement stmt = null; resultet rset = null; try {system.out.out.out.out.out.out.Outln("); dataSource.getConnection(); System.out.println( "Creating Statement。"); stmt = conn.createStatement(); system.out.println( "実行ステートメント。"); rset = stmt.executequery( "select * from person"); system.out.out.println( "); 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(sqlecsection(e.) {try {if(rset!= null)rset.close();} catch(例外e){} try {if(stmt!= null)stmt.close()catch(excepsed e){} try {if(conn!= null)conn.close();} catch(Exception E){}}}}}}}}}}}}}}}}} connecturi){//接続アドレスの設定接続ファクトリー接続機能= new drivermanagerconnectionfactory(connecturi、null); //接続ファクトリーPoolableConnectionFactoryを作成するpoopleableconnectionfactory(connectionfactory); PoolingDriver PoolingDataSource DataSource = new PoolingDataSource(ConnectionPool); return dataSource;}}}8。DbutilsapacheOrganizationが提供するリソースJDBCツールクラスライブラリ。これは、JDBCの単純なカプセル化、従来の動作データベースクラスの二次カプセル化であり、結果をリストに変換できます。 、そして、それはプログラムのパフォーマンスに影響しません。
dbutilsクラス:スタートアップクラス
結果Ethandlerインターフェイス:変換タイプインターフェイス
MapListhandlerクラス:実装クラス、レコードをリストに変換します
BeanListhandlerクラス:クラスを実装し、レコードをリストに変換し、レコードをJavabeanタイプのオブジェクトに作成します
QRERYRUNNERクラス:SQLステートメントを実行するクラス
import org.apache.commons.dbutils.DbUtils;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanListHandler;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.list; //パブリッククラスのbeanlistsに変換{public static void main(string [] args){connection conn = null; string url = "jdbc:mysql:// localhost:3306/ptest"; string jdbcdriver = "com.mysql.dbc.driver"; driver "; driver"; "ptest"; dbutils.loaddriver(jdbcdriver); try {conn = drivermanager.getConnection(url、user、password); quyryrunner qr = new queryrunner(); list results =(list)qr.query(conn、 "select id、from person"、new beanshandler(inter from(inter)fion(inter) results.size(); person p =(person)results.get(i); out.println( " + p.getid() +"、name: " + p.getname();}} catch(sqlexception e){e.printstacktrace(); id; private string name; // omit set、get method} import org.apache.commons.dbutils.dbutils; import org.apache.commons.dbutils.queryrunner; import org.apache.commons.dbutils.handlers.maplishandler; import java.sql.conneftion; java.sql.sqlexception; Import java.util.list; import java.util.map; // public class maplists {public static void main(string [] args){connection conn = null; string url = "jdbc:mysql:// localhost:3306/ptest"; string jdbcddbcdrive "; "com.mysql.jdbc.driver"; string user = "root"; string password = "ptest"; dbutils.loaddriver(jdbcdriver); try {conn = drivermanager.getConnection(URL、ユーザー、パスワード); queryrunner qr = new queryrunner(); maplisthandler()); for(int i = 0; i <results.size(); i ++){map map =(map)results.get(i); system.out.println( "id:" + map.get( "id") + "、name:" + map.get( "name");}} catch(sqlexception e){e.printstacktrace(); {dbutils.closequetly(conn);}}}9.電子メールで提供されるオープンソースAPIは、Javamailのカプセル化です。
// commonsを使用して電子メールを送信しますemails public static void main(string args []){email email = new simplemail(); email.sethostname( "smtp.googlemail.com"); email.setsmtpport(465); email.setauthenticator(new defaultAuthenticator( "username"、 「パスワード "))10。fileuploadjava webファイルアップロード機能。
//公式例://*ファイルアップロードリクエストBoolean isMultipArt = servletfileupload.ismultipartContent(リクエスト); //アイテムのリストがあります//アプリケーションが最も単純なケースに近い場合、上記の処理は十分です。しかし、時々私たちはまだより多くの制御が必要です。 //以下はいくつかの制御オプションです。 servletfileupload(Factory); //最大アップロードサイズupload.setsizemax(yourmaxrequestsize); //すべてのリクエストリスト/ * fileitem */items = upload.parserequest(リクエスト); yourtempdirectory); //解析が完了したら、アイテムのリストをさらに処理する必要があります。 //アップロードされたアイテムの処理iterator iter = items.iterator(); while(iter.hasnext()){fileItem item =(fileItem)iter.next(); if(item.isformfield()){processformfield(item);} else {processuploadedfile(item);}} //データが単純なフォームデータであるかどうかを区別します。 // processUploadedFile if (!item.isFormField()) {String fieldName = item.getFieldName();String fileName = item.getName();String contentType = item.getContentType();Boolean isInMemory = item.isInMemory();long sizeInBytes = item.getSize();//...Omit steps}//For these items, we usuallyそれらをファイルに書き込むか、それらをストリームに変換します//ファイルアップロードif(writetofile){file uploadedfile = new file(...); item.write(uploadedfile);} else {inputstream.getinputStream();メモリバイトのファイルアップロード[] data = item.get(); // ...省略ステップ// {system.out.println( "私たちは現在項目を読んでいます" + pitems); if(pcontentlength == -1){system.out.println( "これまでのところ、 + pbytesRead +"バイトが読まれました。 ");} else {system.out.println(" read。 ");}}}; upload.setProgressListener(ProgressListener);11。HTTPCLIENは、HTTPCOREに基づいて実装されたHTTP/1.1互換HTTPクライアントです。一連の再利用可能なクライアント認証、HTTPステータスメンテナンス、およびHTTP接続管理モジュールを提供します。
//メソッドインポートjava.io.ioexception; import org.apache.commons.httpclient。 httpclient httpclient httpclient = new httpclient(); // get method getMethod getMethod = new getMethod( "http://www.ibm.com"); //システムが提供するデフォルトの回復ポリシーを使用してシステムが提供するデフォルトの回復ポリシーを使用するインスタンスのインスタンスgetMethod.getParams()。setParameter(httpmethodparams.retry_handler、new defaulthtpmethodretryhandler()); try {// getMethod int statusCode = httpclient.executemethod(getMethod); if(statuscode!= httpstatus.sc_ok){system.err.println( "method failed:" + getMethod.getStatusline());} // read content byte [] responsebody = getMethod.getResponseBody(); //ハンドルコンテンツsystem.out.Outcempoltプロトコルが間違っているか、返されたコンテンツが問題のあるシステムである可能性があります。 getMethod.releaseConnection();}}}} //ポストメソッドインポートjava.io.ioexception; Import org.apache.commons.httpclient class postsame {public static void main(string [] args){// httpclient httpclient httpclient = new httpclient()のインスタンスを作成します。 namevaluepair [] data = {new nameValuePair( "id"、 "youusername")、new namevaluepair( "passwd"、 "yourpwd")}; // // postmethod postmethod.setRequestbody(data); httpclientは、post and put // 301や302などの後続のサービスを必要とするリクエストの転送を自動的に処理できません(statuscode == httpstatus.sc_movedently || statuscode == httpstatus.sc_moved_temperaly){//ステアリングの演説を開始します。 postmethod.getResponseHeader( "location"); string location = null; if(locationheader!= null){locationheader.getValue(); system.out.println( "ページは" + locationにリダイレクトされました);}12。IOは、java.ioが操作ファイルを拡張するのに非常に便利です。
// 1。ストリーム//標準コードを読む:inputstream in = new url( "http://jakarta.apache.org").openstream(); try {inputStreamReader inr = new inputstreamReader(in); bufferedReader buf = new BufferedReader(inr); );}}最後に{in.close();} // ioutils inputstream in = new url( "http://jakarta.apache.org").openstream(); try {system.out.println(ioutils.tostring(in));ファイルファイル= new file( "/commons/io/project.properties"); list lines = fileutils.readlines(file、 "utf-8"); // 3。残りのスペースを表示long freespace = filesystemutils.freespace( "c:/");13。ラングは、主にキャラクター、アレイなどの操作などのパブリックツールのコレクションです。
// 1 2つの配列のマージ:org.apache.commons.lang。 Arrayutils // 2つの配列を配列に結合する必要がある場合があり、Arrayutilsを使用するのは非常に便利です。例は次のとおりです:private static void testarr(){string [] s1 = new String [] {"1"、 "2"、 "3"}; string [] s2 = new String [] {"a"、 "b"、 "c"}; string [] s =(string [])arrayutils.addall(s1、s2); {system.out.println(s [i]);} string str = arrayutils.tostring(s); str = str.substring(1、str.length() - 1); system.out.println(str + ">>" + str.length();} //文字列が数値(0〜9)で構成されているかどうかを判断します。もしそうなら、trueを返しますが、この方法では小数点を認識しません。Stringutils.isnumer( "454534"); // true // 4を返すことに注意してください。クラス名system.out.println(classutils.getShortClassName(test.class))を取得します。 //パッケージ名System.out.println(classutils.getPackageName(test.class))を取得します。 //5.Numberutils System.out.println(numberutils.StringToint( "6")); // 6。 5桁のランダムな文字と数字system.out.println(randomsstringutils.randomalphanumeric(5)); //7.stringescapeutils system.out.println(stringescapeutils.escapehtml( "<html>")); //出力結果は<html> system.out.println(stringescapeutils.escapejava( "string")); System.out.println(stringutils.isblank( "")); // system.out.println(stringutils.join(test、 "、")); //右に文字を追加するために右に文字を追加して、6つのsystem.out.println(stringutils.rightspad( "abc"、 'abc "、' t '); System.out.println(stringutils.capitalize( "abc")); //文字列からすべてのホワイトスペースを削除するすべてのスペースsystem.out.println(stringutils.deletewhitespace( "abc")); "ba")); //左system.out.println(stringutils.left( "abc"、2)); system.out.println(numberutils.stringtoint( "33"));14。LoggingはJavaロギングインターフェイスを提供します。これは、軽量の両方で考慮され、特定のログ実装ツールに依存していません。
Import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; public class commonlogtest {private static log = logfactory.getlog(commonlogtest.class); {log.error( "error"); log.debug( "debug"); log.warn( "warn"); log.info( "info"); log.trace( "trace"); system.out.println(log.getClass();}}}} 15.バリデーターは一般的な検証システムであり、クライアント側とサーバー側のデータ検証フレームワークを提供します。
検証日
//日付確認dateValidator validator = datevalidator.getInstance(); // vilify/converty date date date foodate = balidate(foostring、 "dd/mm/yyyy"); if(foodate == null){//エラーは日付のリターンではありません;}式検証
//パラメーターBoolean CaseSensitive = false; string regex1 = "^([az]]*)(?:// - )([az]*)*$" string regex2 = "^([az]]*)$"; string = new String [] {] {regex1、regex1}; RegexValidator(Regexs、CaseSensitive); // Boolean boolean validator.isvalid( "abc-def"); // returns rurens returns returns returns returns ruptles ruptles = validate( "abc-def");構成ファイルで検証を使用します
<form-validation> <global> <validator name = "required" classname = "org.apache.commons.validator.testvalidator" method = "validaterequired" methodparams = "java.lang.object、org.apache.commons.Validator.field"/> <form-validation> <global> <validator name = "required" classname = "org.apache.commons.validator.testvalidator" method = "validaterequired" methodparams = "java.lang.object、org.apache.commons.Validator.field"/>依存関係= "要求"> <arg0 key = "nameform.firstname.displayname"/> </field> <field property = "lastname" depends = "execress"> <arg0 key = "nameform.lastname.displayname"/> </formset> </form-validation> form-validation>
検証クラス
org.apache.commons.validator.requirednametest //検証構成ファイルinputStream in = this.getClass()。getResourceAsstream( "validator-name-required.xml"); validAtorresources resources = new validAtorresources(in); name name = new name(); validator validator(resources、 "nameform"); // parameter validator.setparameter(validator.bean_param、name); map result = null; // validator.validate(); if(results.get( "firstName")= null) ((integer)results.get( "firstName"))。intvalue();}
要約します
上記は、この記事のApache Commonsツールセットコードのすべての詳細な説明です。すべての人に役立つことを願っています。興味のある友人は、このサイトの他の関連トピックを引き続き参照できます。欠点がある場合は、それを指摘するためにメッセージを残してください。このサイトへのご支援をありがとうございました!