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

從零構建 REST 風格 MVC 框架:WebWind 核心架構設計全解析

     編輯:Java 相關知識

傳統 MVC 框架(Struts、WebWork)習慣將 URL 映射到 Action 類,導致 URL 帶有 .do、.action 後綴,不利於 SEO 與用戶體驗。REST 風格 URL(如 /blog/1234/5678)簡潔語義化,已成現代 Web 開發標配。本文完整復現一個原生支持 REST 的輕量 MVC 框架 —— WebWind 的核心設計思路與關鍵代碼。

設計目標:方法級映射與零 XML 配置

WebWind 打破「一個 URL 對應一個 Controller 類」的傳統,直接將 URL 映射到方法,並通過 @Mapping 註解聲明路由模板:

public class Blog {
    @Mapping("/create/$1")
    public void create(int userId) { ... }

    @Mapping("/display/$1/$2")
    public void display(int userId, int postId) { ... }
}

$1、$2 為路徑變量,自動綁定為方法參數,類型轉換由框架完成。Controller 無需實現任何接口,極大降低侵入性。

IoC 容器集成:解耦框架與組件管理

框架不應管理 Bean 生命週期,而是通過 ContainerFactory 統一抽象:

public interface ContainerFactory {
    void init(Config config);
    List<Object> findAllBeans();
    void destroy();
}

分別實現 SpringContainerFactory(基於 ApplicationContext)與 GuiceContainerFactory(基於 Injector),掃描所有 Bean 的 public 方法,註冊帶 @Mapping 的方法。擴展新容器只需實現接口,符合開閉原則。

請求分發核心:UrlMatcher 與 Dispatcher

將 /blog/$1/$2 編譯為正則 ^\\/blog\\/([^\\/]*)\\/([^\\/]*)$,預編譯 Pattern 提升匹配性能。Dispatcher 維護 UrlMatcher -> Action 映射表,請求到來時遍歷匹配,提取參數構造 Execution,通過反射調用目標方法:

public Object execute() throws Exception {
    return action.method.invoke(action.instance, args);
}

異常處理中解包 InvocationTargetException 拋出真實原因,便於上層統一異常處理。

靜態資源透傳與安全防護

因 DispatcherServlet 映射為 /(默認 Servlet),所有未匹配請求均進入框架。StaticFileHandler 負責靜態文件服務,關鍵安全點:攔截 /WEB-INF/ 路徑防止敏感文件洩露,並支持 If-Modified-Since 條件請求優化緩存。

模板引擎抽象:JSP 與 Velocity 統一適配

定義 TemplateFactory 與 Template 接口,JspTemplate 通過 RequestDispatcher.forward() 渲染,VelocityTemplate 則調用 Velocity 引擎。Controller 返回 TemplateRenderer 即可實現視圖解耦:

return new TemplateRenderer("user/profile.vm", modelMap);

web.xml 中指定 template=Velocity 即可全局切換引擎。

攔截器鏈:輕量級橫切關注點處理

不同於 Filter 作用於整個請求鏈,攔截器僅圍繞 Controller 方法執行,適合事務管理、權限檢查等場景。InterceptorChainImpl 遞歸調用鏈上各攔截器,最後執行 Execution.execute(),最終結果交由 handleResult() 處理:String 直接輸出、redirect: 前綴重定向、Renderer 渲染視圖。

文件上傳:零配置集成 Commons FileUpload

自定義 MultipartHttpServletRequest 繼承 HttpServletRequestWrapper,啟動時通過 Class.forName 檢測 Commons FileUpload 類是否存在,自動開啟功能。覆寫 getParameter* 方法使表單字段透明訪問,getFileInputStream() 提供文件流讀取,客戶端代碼無感知。

Filter 替代方案:DispatcherFilter

若不想佔用默認 Servlet,可使用 DispatcherFilter 映射 /*,未匹配請求調用 chain.doFilter() 交給容器默認 Servlet 處理靜態資源,效率更高。

ActionContext:ThreadLocal 實現 Servlet 對象訪問

在 Dispatcher.handleExecution() 中 ThreadLocal 綁定 HttpServletRequest 等對象,Controller 通過 ActionContext.getActionContext() 隨時獲取,執行完畢 finally 塊清理,避免內存洩漏。

WebWind 雖是教學級框架,但其設計精準回應了 REST 化、註解驅動、IoC 集成、模板解耦、攔截器、文件上傳等現代 Web 開發核心需求,是理解 MVC 內核機制的優秀範本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved