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 도구의 캡슐화. |
| 랭 | Java 기본 객체 메소드를위한 공구 클래스 패키지 : StringUtils, Arrayutils 등 |
| 벌채 반출 | Java 로깅 인터페이스를 제공합니다. |
| 유효성 검사기 | 클라이언트 및 서버 측을위한 데이터 확인 프레임 워크를 제공합니다. |
1. Beanutils는 객체, 속성 복사 등과 같은 Javabean에 대한 다양한 작업을 제공합니다.
// 1. 클로닝 객체 // 복제 된 개체 공개 클래스 사람으로 사용할 새로운 정상 자바 빈을 만듭니다 {private String email = ""; private String email = ""; private string email = ""; private int age; // yamit set} // 메인 메서드의 코드가 다음과 같습니다. import java.lang.reflect.invocationTargetexception; hampor javocation javocmap; 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) {person = new person (); {// 복제 된 사람의 person2 = (person) beanutils.clonebean (person); system.out.println (person2.getName ()+">>"+person.20.getage ());} catch (불법 행사 exception e) {e.printstackTrace ();} catch (e.printiationExceptrace () {e.printsctrace (); {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 person (); populate (person, map); // 위의 코드를 통해 이미 지정된 가치가 있습니다. // 다음과 같이 Bean을지도 객체로 변환하십시오. Map Map = beanutils.describe (person)2. Betwixt XML 및 Java 객체가 변환됩니다.
// 1. javabean을 XML 콘텐츠로 변환 // 새로운 사람 클래스 공개 클래스 개인 {private string public class person; private int age;/** 반사를 통해 Bean을 만들 수 있어야합니다*/public personbean () {} public personbean (string name, int age) {name = name; this.age = age;} // omit set, perval string get "{return"{return "{return" " ', age =' + age +" '] ";}} // writeApp 클래스 생성 : import java.io.stringwriter; import org.apache.commons.betwixt.io.beanwriter; public class writeApp {/*** XML로 변환하십시오. */public static final void main (string [] args)은 예외를 던집니다. {// StringWriter를 먼저 생성합니다. String writer outputWriter = new StringWriter (); // betwixt는 여기에 Bean을 조각으로 작성하여 XML 컨텐츠를 완료하려면 extputWriter.write.write.wwith ( "xml <xml 버전에 써야합니다. 인코딩 = 'UTF-8'?>/n "); // 콩나물을 만듭니다. beanwriter beanwriter = new Beanwriter (outputwriter); // betwixt // configure congring revery는 Java Docs 또는 최신 문서를 참조하십시오. beanwriter.getxmlintrospector (). getConfiguration (). stattributesforPrimitives (false); beanwriter.getBindingConfiguration (). setMapids (false); beanwriter.enablePrettyPrint (); //이 장소가 XML의 이름으로 사용되지 않는다면, betwixt가 무엇입니까? beanwriter.write ( "Person", New Personbean ( "John Smith", 21)); // output result system.out.out.println (outputwriter.toString ()); // betwixt는 문서보다는 조각을 씁니다. 왜냐하면 작가 나 스트림을 자동으로 닫지 않지만 여기에 예제가없고 더 많이 할 수 없습니다. XML을 javabean import java.io.stringReader로 변환하십시오. import org.apache.commons.betwixt.io.beanreader; public class readapp {public static final void main (String Args []) 예외 {// 먼저 XML을 만듭니다. 이것은 예제이기 때문에 XML 컨텐츠 stringReader xmlreader = new StringReader ( "<? XML 버전 = '1.0'인코딩 = 'utf-8'?> <person> <ege> 25 </age> <name> James Smith </name> </person>"); // BeanReader BeanReader = New BeanReader (//); beanReader.getXmlintroSpector (). getConfiguration (). setAttributesforPrimitives (false); beanReader.getBindingConfiguration (). setMapids (false); // Bean XML이 beanreader.registerbeanclass로 변환 될 Bean XML이 무엇인지 알 수 있도록 Beans를 등록하십시오. = (PersonBean) BeanReader.Parse (XMLREADER); // 출력 결과 System.out.println (person);}}3. Codec은 Base64, Hex, MD5, 음성 및 URL 등과 같은 일부 공개 코덱 구현을 제공합니다.
// Base64 Codec private static string encodetest (string str) {Base64 Base64 = new Base64 (); try {str = base64.encodetostring ( "utf-8");} catch (unsupportedencodingexception e) {e.printstacktrace (); str;} private static void decodetest (string str) {Base64 Base64 = new Base64 (); // strrays.tostring (base64.decodebase64 (str)); str = new String (base64.decodebase64 (str)); System.out.println ( "Base64 디코딩 :"+str);}4. 컬렉션은 java.util을 확장하고 데이터를 매우 유연하게 처리합니다.
org.apache.commons.collections 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 interface를 구현하는 클래스 세트.
org.apache.commons.collections.keyValue는 수집 및 키/값 매핑과 관련된 일련의 클래스를 구현합니다.
org.apache.commons.collections.list java.util.list interface를 구현하는 클래스 세트.
org.apache.commons.collections.map 시리즈 인터페이스를 구현하는 클래스 세트를 맵핑하십시오.
org.apache.commons.collections. 세트 시리즈 인터페이스를 구현하는 클래스 세트 설정
/** * 세트 */OrderEdMap Map = New LinkedMap (); map.put ( "5", "5"); map.put ( "Six", "6"); map.put ( "Seven", "7"); map.firstkey (// "5"Map.NextKey ( "Five"); // returns "6") "Seven"/** * Key를 통해 값을 가져옵니다 * 값을 통한 키 * 값을 얻습니다 * 값 스위치 키 및 값 맵 */bidimap bidi = new treebidimap (); bidi.put ( "6", "6"); bidi.get ( "6"); // returns "6"bidi.getkey ( "6"); // retip "six"// bidi.removevalue ( "6"); // 맵핑 vidimap vidivers = bidi.inversebidimap (); // 키와 값 스왑 시스템이있는 맵을 반환합니다. 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"); CollectionUtils. List2); System.out.println (C);
5. 커먼즈 포장 및 압축 클래스 라이브러리를 압축합니다.
// 압축 객체 생성 ziparchiveAntry entry = new ZiparchiveEntry ( "compresstest"); // 압축 될 파일 f = 새 파일 ( "e : //test.pdf"); fileInputStream fis = new FileInputStream (f); // ZipOutputStream Zipoutput prut = new 아웃 스트림 (new). file ( "e : //test.zip"); zipoutput.putarchiveEntry (Entry); int i = 0, j; while ((j = fis.read ())! = -1) {zizoutput.write (j); i ++; system.out.println (i); Zipoutput.closearchiveEntry (); zipoutput (); fisclose ();6. 구성은 구성 파일을 처리하는 데 도움이되며 많은 스토리지 방법을 지원합니다.
1. 속성 파일
2. XML 문서
3. 속성 목록 파일 (.Plist)
4. Jndi
5. JDBC 데이터 소스
6. 시스템 속성
7. 애플릿 매개 변수
8. 서블릿 매개 변수
// 속성의 간단한 예제 #usergui.properties colors.background = #fffff colors.foreground = 000080 Window.width = 500 Window.height = 300 PropertiesConfiguration config = new PropertiesConfiguration ( "USERGUI.Properties"); COLUNS.BACKGRUNE ", #000000); config.save (); config.save ( "usergui.backup.properties); // 정수 정수를 저장합니다.
7. DBCP (데이터베이스 연결 풀)는 Jakarta Commons-Pool Object Pool 메커니즘에 의존하는 데이터베이스 연결 풀입니다. Tomcat의 데이터 소스는 DBCP를 사용합니다.
import javax.sql.datasource; import java.sql.connection; import java.sql.statement; import java.sql.resultset; import java.sql.sqlexception; import org.apache.commons.pool.objectpool; import org.apjectpach.commons.pool.mpool org.apache.commons.dbcp.connectionfactory; import org.apache.commons.dbcp.poolingdatasource; import org.apache.commons.dbcp.dbcp.poolableconnectionfactory; import org.apache.commons.dbcp.dbcp.dbcp.driverconnection factory; // 공식적인 수업 gourcess {// 공식적인 수업 척. main (string [] args) {system.out.println ( "jdbc driver"); try {class.forname ( "oracle.jdbc.driver.oracledriver");} catch (classNotFoundException e) {e.printstacktrace ();} system.out.println ( "done."); // 시스템. " Source "); DataSource DataSource = SetupDatasource ("JDBC : Oracle : Thin : @localHost : 1521 : Test "); System.out.println ("done. "); // Connection Conn = null; stmt = null; resultSet = null; try {Systion.println ("Connection = "); DataSource.getConnection (); system.out.println ( "state. rset.getmetadata (). getColumnCount (); while (rset.next ()) {for (int i = 0; i <= numcols; i ++) {system.out.print ( "/t"+rset.getString (i)); {try {if (rset! = null) rset.close ();} catch (예외 e) {} try {if (stmt! = null) stmt.close () catch (예외 e) {} try (conn! = null) conn.close () catch (Exception e)}}}}}}}}}} ConnectURI) {// 연결 주소 설정 연결 요소 ConnectionFactoryFactory = 새로운 DriverManagerConnectionFactory (Connecturi, NULL); // 연결 공장 생성 Factory PoolbeLeConnectionFactory PoolBeLeConnectionFactory = New PoolBeLeConnectionFactory (ConnectionActory); // PULLBLEBLECONCONTORY의 인스턴스 GET GET get the GEL PoolingDatasource DataSource = New PoolingDatasource (ConnectionPool); Return DataSource;}}}8. Dbutilsapache Organization에서 제공하는 리소스 JDBC 도구 클래스 라이브러리. JDBC의 간단한 캡슐화, 기존 운영 데이터베이스 클래스의 보조 캡슐화이며 결과를 목록으로 변환 할 수 있습니다. 그리고 그것은 프로그램의 성능에 영향을 미치지 않습니다.
DBUTILS 클래스 : 스타트 업 클래스
resultsEthandler 인터페이스 : 변환 유형 인터페이스
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; java.util.list; // 공개 클래스 beanlists를 나열하도록 변환 {public static void main (string [] args) {Connection Conn = null; String URL = "jdbc : mysql : // localhost : 3306/ptest"; String jdbcdriver = "com.mysql.jdbc.driver"; String user = "; "ptest"; dbutils.loaddriver (jdbcdriver); try {conn = drivermanager.getConnection (url, user, password); QueryRunner qr = new QueryRunner (); List Results = (목록) QR.Query (Conn, "선택 ID, 사람의 이름", New Beanlisthandler (person.class); i ++) {person p = (person) results.get (i); system.out.println ( "id :" + p.getid () + ", 이름 :" + p.getname ());}} catch (sqlexception e) {e.printstacktrace ();} 마침내 {dbutils.closequietly (conn);}}}}}}}}}}}}} 이름; // avit set, get} import org.apache.commons.dbutils.dbutils; import org.apache.commons.dbutils.queryRunner; import org.apache.commons.dbutils.handlers.maplisthandler; import java.sql.connection; java.sql.drivermanger; java.sql.sqlexception; import java.util.list; import java.util.map; // 공개 클래스 메이플리스트 {public static void main (String [] args) {Connection Conn = null; String url = "jdbc : mysql : // localhost : 3306/ptest"; String jdbcdr "; "com.mysql.jdbc.driver"; String user = "Root"; String password = "ptest"; dbutils.loaddriver (jdbcdriver); try {conn = drivermanager.getConnection (URL, 사용자, 암호); QueryRunner qr = new queryRunner () qr.query (Conn, "Querceer (conn,", ",", ",", "QR." maplisthandler ()); for (int i = 0; i <results.size (); i ++) {map map = (map) results.get (i); system.out.println ( "id :" + map.get ( "id")), 이름 : " + map.get ("name "));}} catch (sqlexection e) {e.printstacktrace ();}. {dbutils.closequietly (conn);}}}9. 이메일로 제공되는 오픈 소스 API는 Javamail의 캡슐화입니다.
// commons를 사용하여 이메일 보내기 공개 정적 무효 기본 (String args []) {이메일 이메일 = new Simplemail (); email.sethostName ( "smtp.googlemail.com"); email.setsmtpport (465); email.setauthenticator ( "username", "password"); email.setsslonconnect (true); email.setfrom ( "[email protected]"); email.setsubject ( "testmail"); email.setmsg ( "이것은 테스트 메일 ... :-)"); email.addto ( "[email protected]"); email.send ();};10. FileUpload Java 웹 파일 업로드 기능.
// 공식 예 : //* 파일 업로드 요청이 있는지 확인하십시오. 부울 ismultipart = servletfileupload.ismultipartContent (요청); // 항목 목록이 있습니다. // 응용 프로그램이 가장 간단한 경우에 가까운 경우 위의 처리로 충분합니다. 그러나 때때로 우리는 여전히 더 많은 통제가 필요합니다. // 다음은 몇 가지 제어 옵션입니다 : // 디스크 기반 파일에 대한 공장 생성 디스크 파일 팩토리 팩토리 = 새로운 디스크 파일 시티 플렉스 (); // 팩토리 제약 조건 설정 팩토리 (yourMaxMemorySize); factory.setrepository (yourtempDirectory); 새로운 파일 handletler upletfilefiletfilefile upload up upload upload upload upload uplok ServletFileUpload (Factory); // 최대 업로드 크기 업로드 업로드를 설정합니다 .SetSizEmax (YourMaxRequestSize); // 모든 요청 목록/ * fileItem */items = upload.parserequest (요청); // 디스크 기반 파일 디스크 파일 정보 공장을위한 공장 생성 (new diskfileitemfactory). yourtempdirectory); // 구문 분석이 완료되면 항목 목록을 추가로 처리해야합니다. // 업로드 된 항목을 처리합니다 Ierator 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 (); item.isinMemory (); isinmemory (); intiM.getsize (); 파일 또는 스트림으로 변환 // 파일 업로드 if (writeTofile) {file uploadedfile = new File (...); item.write (uploadedFile);} else {inputStream uploadedStream = item.getInputStream (); // uploadededStream.close ();} // 또는이를 제가에 따라 제가로 바꾸면서 제출합니다. Memory Byte [] data = item.get (); // ... 생략 된 단계 //이 파일이 실제로 크면 서버에 얼마나 많은 전송 된 양을보고하여 사용자가 업로드 프로세스를 이해할 수 있도록 // 진행 리스너 ProgressListener ProgressListener = New ProgressListener () {public void update (long pbytesread, long pitem)를 이해할 수 있습니다. {system.out.println ( "우리는 현재 항목" + pitems); if (pcontentLength == -1) { "지금까지" + pbytesread + "바이트가 읽혔습니다."); 읽기. ");}}}; upload.setProgressListener (ProgressListener);11. HTTPCLIEN은 HTTPCore를 기반으로 구현 된 HTTP/1.1 호환 HTTP 클라이언트입니다. 일련의 재사용 가능한 클라이언트 인증, HTTP 상태 유지 관리 및 HTTP 연결 관리 모듈을 제공합니다.
// 메소드 가져 오기 java.io.ioexception; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.getmethod; import org.apache.commons.httpclient.params.httpmethodparams; public void void void void (string). httpclient httpclient httpclient의 인스턴스 구성 httpclient = new httpclient (); // get method get method getmethod = new getMethod ( "http://www.ibm.com"); // 시스템이 제공 한 기본 복구 정책을 사용하십시오. getMethod.getParams (). setParameter (httpmethodparams.retry_handler, new defaulthttpmethodretryhandler ()); try {// getMethod int statescode = httpclient.executemethod (getMethod); if (statusCode! = httpstatus.sc_ok) {system.err.println ( "메소드 실패 :" + getMethod.getStatusline ());} // 컨텐츠 byte [] response [] responce = getMethod.getResponsebody (); // 핸들 컨텐츠 System.out.out.println (new String (respintbody)); 프로토콜이 부정확하거나 반환 된 컨텐츠가 문제가있는 System.out.out.println ( "제공된 HTTP 주소!"); e.printstacktrace ();} catch (ioException e) {// 네트워크 예외가 발생했을 수 있습니다. 메소드 import java.io.ioexception; import org.apache.commons.httpclient.httpclient.httpclient.httpclient.httpclient.httpclient.httpclient.httpclient.httpclient.httpclient.httpclient.httpclient.httpclient.httpclient.method.methods.postMethod; import org.apache.commons.httpclient.httpmethodparams; public void void main (string an) httpclient httpclient httpclient의 인스턴스 = new httpclient (); // post method string url = "http://www.oracle.com/";postmethod postmethod = new postmethod (url); // 각 field namevaluepair의 값을 채우십시오. "youusername"), 새로운 namevaluepair ( "passwd", "yourpwd")}; // 양식의 값을 postmethod postmethod.setrequestbod (data)에 넣습니다. int statuscode = httpclient.executemethod (postmethod); // httpclient는 다음과 같은 후속 서비스를 필요로 할 수 없습니다. 그리고 // 301 또는 302 if (statusCode == httpstatus.sc_moved_permanently || statusCode == httpstatus.sc_moved_temporally) {// 시작 헤드러 위치 헤드에서 스티어링의 주소를 꺼냅니다. LocationHeader.getValue (); system.out.println ( "페이지가" + location);} else {system.err.println ( "위치 필드 값은 null입니다.");} return;}}}로 리디렉션되었습니다.12. IO는 java.io가 작동 파일을 확장하는 데 매우 편리합니다.
// 1. 스트림 읽기 // 표준 코드 : inputStream in = new URL ( "http://jakarta.apache.org") .openstream (); inputStreamReader inr = new inputStreamReader (in); bufferedReader buf = new BufferedReader (inr); String Line; line);}} 마침내 {in.close ();} // ioutils inputStream in = new URL ( "http://jakarta.apache.org"); openstream (); try {system.out.println (ioutils.toString (in)); {in); 파일 파일 파일을 읽습니다 = 새 파일 ( "/commons/io/project.properties"); list lines = fileUtils.ReadLines (파일, "UTF-8"); // 3. 나머지 공간보기 긴 프리 스페이스 = FileSystemutils.freespace ( "C :/");13. Lang은 주로 문자, 배열 등에 대한 작업과 같은 공개 도구 모음입니다.
// 1 두 어레이를 병합하십시오 : org.apache.commons.lang. Arrayutils // 때때로 우리는 두 개의 배열을 배열로 결합해야하며 Arrayutils를 사용하는 것이 매우 편리합니다. 예제는 다음과 같습니다. private static void testarr () {string [] s1 = new String [] { "1", "2", "3"}; String [] s2 = new String [] { "a", "b", "c"}; String [] s = (String []) arrayutils.addall (s2); for (int i = 0; i <s.length; {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.isnumeric ( "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 (RandomStringUtil.randomalphanumeric (5)); //7.stringescapeutils System.out.println (StringEscapeutils.escapehtml ( "<html>")); // 출력 결과는 <html> system.out.println (StringEscapeutils.scapejava ( "String")); acpapejava (8.Stringutils) ")); // System.out.println (StringUtils.join (test,", "))에 의해 배열의 내용을 분리하여 6 System.out.println (StringUtils.rightPad ("ABC ", 6, '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 로깅은 Java 로깅 인터페이스를 제공하며, 이는 경량을 모두 고려하고 특정 로그 구현 도구에 의존하지 않습니다.
import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; public class commonlogtest {private static log = logfactory.getlog (commonLogtest.class); // log print 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는 일반 확인 시스템으로 클라이언트 및 서버 측을위한 데이터 검증 프레임 워크를 제공합니다.
확인 날짜
// 날짜 확인 날짜 확인 날짜 확인 날짜 확인 날짜 validator validator = dateValidator.getInstance (); // 검증/변환 날짜 날짜 foodate = validator.validate (foostring, "dd/mm/yyyy");
표현 검증
// 매개 변수 boolean caseensitive = false; String regex1 = "^([az]*) (? : //-) ([az]*)*$"string regex2 = "^([az]*) $"; String [] regexs = new String [] {Regex1, Regex1}; regexvalidator (Regexs, Casesensitive); // retify retuds boolean boolean valid = validator.isvalid ( "abc-def"); // string string result = validator.validate ( "abc-def"); // retry retrys [] groups.match ( "abc-def");구성 파일에서 확인을 사용하십시오
<form-validation> <global> <validator name = "필수"ClassName = "org.apache.commons.validator.testValidator"method = "validateRequired"MethodParams = "java.lang.object, org.apache.commons.validator.field"/> </formset> </form-validation> <form-validation> <global> <validator name = "필수"ClassName = "org.apache.commons.validator.testValidator"method = "validateRequired"methodParams = "java.lang.object, org.apache.commons.validator.field"/> <formset> <form amams = ""forms "" ""forms "" " 종속 = "필수"> <arg0 key = "nameform.firstname.displayName"/> </field> <필드 속성 = "lastName"부양 = "필수"> <arg0 key = "nameform.lastname.displayName"/> </formset> </form-validation>
확인 클래스
org.apache.commons.validator.requirednameTest의 Excelpts // 검증 구성 파일 inputStream in = this.getClass ( "validator-name-required.xml"); validatorResources Resources = New ValidatorResources (in); 이름 이름 = new name (); validator validator = new validator (resources, "nameform"); // 매개 변수 validator.setparameter (validator.bean_param, name); map results = null; // 결과 = validator.validate (); if ( "firstname") == null) {// veryfy and wathify} ((Integer) results.get ( "FirstName")). intValue ();}요약
위의 내용은이 기사에서 Apache Commons 도구 세트 코드에 대한 자세한 설명입니다. 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구는이 사이트의 다른 관련 주제를 계속 참조 할 수 있습니다. 단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!