萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Spring + Spring MVC + MyBatis + Shiro 高效能 Web 架構實戰:從 Maven 到完整專案結構

專案簡介

採用「最適技術、持續最佳實踐」原則構建的企業級快速開發框架 quick4j,原始碼:GitHub。

技術棧

  • 後端:Spring 4.0.2 + Spring MVC + MyBatis 3.2.2 + Apache Shiro 1.2.3
  • 建構:Maven 多模組管理依賴
  • 前端:MetroUI 模板
  • 資料庫:MySQL / PostgreSQL,Druid 連線池
  • 其他:Ehcache、Jackson、Netty、Hibernate Validator、AspectJ

專案結構

src/main/java        Java 原始碼
src/main/resources   設定檔、MyBatis XML、屬性檔
src/main/webapp      Web 根目錄 (JSP/靜態資源)
src/test/java        測試碼
pom.xml              Maven 設定

核心設定檔重點

pom.xml

  • 統一版本屬性管理(${spring.version} 等)。
  • MyBatis Generator 插件自動生成 Model/Mapper/XML。
  • 資源過濾開啟 filtering=true 支援屬性檔佔位符。

web.xml

  • ContextLoaderListener 載入 applicationContext*.xml 与 applicationContext-shiro.xml。
  • Spring CharacterEncodingFilter 強制 UTF-8。
  • Shiro DelegatingFilterProxy 代理 shiroFilter。
  • DispatcherServlet 攔截 /rest/*,效能最佳。
  • 錯誤頁面映射 404/500/401。

applicationContext.xml

  • component-scan 掃描 com.eliteams.quick4j。
  • DruidDataSource 連線池參數外部化至 application.properties。
  • MyBatis SqlSessionFactoryBean 掃描 Mapper XML。
  • 宣告式事務:insert/update/delete REQUIRED 回滾;select/count read-only=true 提升查詢效能。
  • CGLIB 代理 (proxy-target-class=true) + @Transactional 支援。
  • Ehcache 整合 Spring Cache 抽象。

Shiro 設定

  • ShiroFilterFactoryBean 定義 filterChainDefinitions:靜態資源 anon、登入頁 anon、其餘 authc。
  • Realm 實作 securityRealm 負責認證授權。
  • Ehcache 快取會話與授權資料。

MyBatis 設定

  • 開啟二級快取 cacheEnabled=true、延遲載入 lazyLoadingEnabled=true、駝峰映射 mapUnderscoreToCamelCase=true。
  • 分頁攔截器 PaginationStatementHandlerInterceptor + PaginationResultSetHandlerInterceptor。

Spring MVC 設定

  • mvc:annotation-driven 整合 Hibernate Validator。
  • MappingJacksonHttpMessageConverter 解決 IE 下載 JSON 問題。
  • InternalResourceViewResolver 前綴 /WEB-INF/views/ 後綴 .jsp。
  • CommonsMultipartResolver 檔案上傳支援 10GB。
  • Shiro 授權註解攔截器 AuthorizationAttributeSourceAdvisor。

資料庫初始化

quick4j.sql 建立 user/role/permission 三表與關聯表,預設 admin/starzou 密碼 123456 (SHA-256)。

啟動驗證

  1. Checkout 專案,Maven 建構。
  2. 建立資料庫執行 SQL。
  3. 修改 application.properties 連線資訊。
  4. 部署至 Tomcat,訪問 /rest/index 進入首頁。

結語

此架構兼顧開發效率與執行效能,歡迎 Fork 貢獻 PR,共同打造更好的 Java Web 脚手架。

copyright © 萬盛學電腦網 all rights reserved