首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Jakarta Commons 組件庫精華指南(上):Web 組件與小程序工具包

     編輯:Java 程式設計入門

項目簡介

Jakarta Commons(現 Apache Commons Proper)旨在提供獨立、可復用的 Java 組件,多源自 Struts、Tomcat 等項目共性代碼抽取。組件間低耦合,專注小范圍功能,適合服務端開發。本文覆蓋 Web 相關與小程序兩大類。

一、小程序類組件

1. CLI:命令行解析器

用途:統一處理命令行參數,支援選項、參數值、幫助生成。


// 定義選項
Options opts = new Options();
opts.addOption("t", false, "show current time");
opts.addOption("n", true, "your name");

// 解析
CommandLineParser parser = new BasicParser();
CommandLine cmd = parser.parse(opts, args);

if (cmd.hasOption("n")) 
    System.out.println("Hello " + cmd.getOptionValue("n"));

核心類:Options、Option、CommandLineParser、CommandLine。

2. Discovery:服務發現機制

用途:運行時定位介面實現類(SPI 模式),支援 META-INF/services、系統屬性、類加載器多種策略。


// 獲取類加載器
ClassLoaders loaders = ClassLoaders.getAppLoaders(MyInterface.class, getClass(), false);
// 發現並實例化
DiscoverClass discover = new DiscoverClass(loaders);
MyInterface impl = (MyInterface) discover.newInstance(MyInterface.class);
impl.doWork();

遵循 Sun Service Provider 規範,適用於插件架構、驅動加載。

3. Lang:java.lang 增強包

核心亮點:

  • StringUtils:capitalize()、isBlank()、join()、split() 等 100+ 靜態方法
  • RandomStringUtils:生成隨機字符串/密碼
  • NumberUtils:數字解析、比較、範圍
  • Builder 系列:ToStringBuilder、EqualsBuilder、HashCodeBuilder、CompareToBuilder —— 一鍵生成高質量標準方法
  • Enum:類型安全枚舉基類(Java 5 前的替代方案)

// ToStringBuilder 示例
public String toString() {
    return new ToStringBuilder(this)
        .append("rate", rate)
        .append("years", years)
        .toString();
}

4. Collections:集合框架擴展

關鍵數據結構:

二、Web 相關組件

1. FileUpload:文件上傳標準實現

特性:RFC1867 兼容、流式解析、閾值自動切換內存/臨時文件、大小限制、進度監聽。


// JSP 表單 enctype="multipart/form-data" method="post"
// Servlet 處理
DiskFileUpload upload = new DiskFileUpload();
List items = upload.parseRequest(request);
for (FileItem item : items) {
    if (item.isFormField()) {
        // 普通字段
    } else {
        // 文件字段
        File saved = new File(uploadDir, FilenameUtils.getName(item.getName()));
        item.write(saved);
    }
}

2. HttpClient:功能完備的 HTTP 客戶端

優於 java.net:連接池、認證、重定向、Cookie 管理、HTTPS/SSL、多線程安全、流式上傳下載。


HttpClient client = new HttpClient();
GetMethod method = new GetMethod("https://www.paypal.com/");
client.executeMethod(method);
String body = method.getResponseBodyAsString();
method.releaseConnection(); // 必須釋放連接回池

支援 GET/POST/PUT/DELETE/HEAD/OPTIONS/TRACE,適合爬蟲、API 集成、代理網關。

3. Net:網絡協議底層工具箱

源自商業產品 NetComponents,封裝 FTP、NNTP、POP3、SMTP、Telnet、Finger、Whois、Time 等協議客戶端。


NNTPClient nntp = new NNTPClient();
nntp.connect("news.example.com");
NewsgroupInfo[] groups = nntp.listNewsgroups();
nntp.disconnect();

統一模式:connect() → 協議命令 → disconnect(),屏蔽 Socket 細節。

總結與展望

Commons 組件體現「小而美」的 Unix 哲學:各司其職、組合強大。下篇將介紹 XML 相關(Betwixt、Digester、Jelly、JXPath)、打包類(Codec、Modeler)及工具類(BeanUtils、Logging、DBCP、Pool、Validator)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
接口/類特性典型場景
Bag / HashBag可重複元素 + 計數詞頻統計、訪問次數
Buffer / BinaryHeap定序移除:FIFO/LIFO/自然序/自定義 Comparator任務隊列、優先級調度
FastArrayList / FastHashMap快/慢模式:讀多寫少場景無鎖讀,寫時複製高併發緩存、配置表
Iterator 擴展數組迭代器、鏈式迭代器、過濾迭代器複雜遍歷邏輯封裝
Comparator 擴展NullComparator、ReverseComparator、鏈式比較器靈活排序規則組合