Struts2 學習筆記(基於尚硅谷佟剛視頻教程)
一、環境搭建與基礎配置
- 無需在 web.xml 顯式定義 Filter,通過
struts.xml 配置
- 屬性引用簡化:
${requestScope.product.productName} → ${productName}
- 請求流程:
product-input.action → input.jsp → product-save.action → Product.save() → details.jsp
二、Action 與 Action 類
- action:一個 Struts2 請求
- Action 類:處理請求的類,需無參構造器,屬性遵循 JavaBean 命名,支持自動類型轉換
- 每個 HTTP 請求創建新實例,線程安全
- 同一 Action 類可包含多個 action 方法
三、訪問 Web 資源
解耦方式(推薦)
ActionContext 獲取 Map:requestMap, sessionMap, applicationMap, parametersMap
- 實現
RequestAware, SessionAware 等接口
- 多 action 方法共用域對象時建議用 Aware 接口
SessionMap 強轉後可調用 invalidate() 銷毀 session
耦合方式
ServletActionContext 獲取原生 API
- 實現
ServletRequestAware 等接口
四、請求擴展名配置
<constant name="struts.action.extension" value="action,do," />
五、ActionSupport 默認行為
- 無
class 屬性時默認使用 ActionSupport,執行 execute() 返回 success
- 需手工驗證、國際化時建議繼承
ActionSupport
六、Result 類型
| type | 說明 |
| dispatcher (默認) | 轉發,同 Servlet 轉發 |
| redirect | 重定向 |
| redirectAction | 重定向到 Action,可攜帶參數 |
| chain | 轉發到另一 Action(保留值棧) |
<result name="index" type="redirectAction">
<param name="actionName">testAction</param>
<param name="namespace">/atguigu</param>
</result>
七、值棧
- 從
ActionContext 獲取 ValueStack
- 兩部分:Map 棧(
OgnlContext,含 request/session/application/parameters/attr)與 對象棧(CompoundRoot,ArrayList 實現,存放 Action 相關對象)
- OGNL 表達式訪問:
[0].property、property(默認棧頂)
s:property 標簽配合 OGNL 讀取值
八、ModelDriven 攔截器流程
ModelDrivenInterceptor 執行 getModel(),將返回對象壓入值棧頂
ParametersInterceptor 將請求參數賦值給棧頂對象屬性
- 注意:
getModel() 不能返回 new Model(),否則 Action 屬性為 null
九、paramsPrepareParamsStack 與 Preparable 接口
- 攔截器順序:
params → modelDriven → params
- 解決編輯操作:先賦 ID → 加載對象壓棧 → 再賦值其他屬性 → 回顯
- 實現
Preparable,提供 prepareXxx() 方法,配置 alwaysInvokePrepare=false 避免調用無參 prepare()
十、國際化
- 資源文件命名:
ActionName_lang_country.properties、package_lang_country.properties、全局 basename_lang_country.properties(需配置 struts.custom.i18n.resources)
- 加載優先級:Action 類同包 → 接口同包 → 父類同包 → ModelDriven model 同包 → 當前包 package.properties → 父包 → 全局 → key 本身
- 頁面用
s:text,Action 中繼承 ActionSupport 調用 getText()
- 切換語言:超鏈接附加
?request_locale=en_US,需為 Struts2 請求觸發 i18n 攔截器
十一、驗證框架
- 聲明式:XML 配置(
ActionName-validation.xml 或 ActionName-alias-validation.xml),支持字段/非字段驗證、短路驗證、國際化消息
- 編程式:在 Action 中實現
validate() 或 validateXxx()
- 驗證失敗自動跳轉
input result
- 類型轉換錯誤默認繼續驗證,可修改
ConversionErrorInterceptor 直接返回 input
- 自定義驗證器:實現
Validator,配置 validators.xml
十二、文件上傳
- 表單:
method="post" enctype="multipart/form-data"
- 依賴:
commons-fileupload, commons-io
- Action 定義三屬性:
File fileField, String fileFieldContentType, String fileFieldFileName(多文件用 List)
- 通過
fileUpload 攔截器參數限制:maximumSize, allowedTypes, allowedExtensions
- 錯誤消息鍵:
struts.messages.error.uploading, struts.messages.error.file.too.large 等
十三、文件下載
- 使用
type="stream" 的 result
- 參數:
contentType, contentLength, contentDisposition (attachment;filename=...), inputName (默認 inputStream), bufferSize
十四、表單重複提交防範
- 現象:不刷新頁面多次點擊提交、提交後回退再提交、轉發後刷新
- 解決:JSP 加
s:token,配置 token 或 tokenSession 攔截器
token:需配置 invalid.token result;tokenSession:靜默忽略後續提交
- 錯誤消息鍵:
struts.messages.invalid.token
十五、自定義攔截器
- 實現
Interceptor 或繼承 AbstractInterceptor
struts.xml 註冊:<interceptor name="hello" class="..."/>
- Action 引用:
<interceptor-ref name="hello"/> + <interceptor-ref name="defaultStack"/>
- 攔截器中不調用
invocation.invoke() 可阻斷後續執行
- 上一篇文章: Java 內部類與巢狀類完整指南:靜態嵌套類、內部類、區域類、匿名類
- 下一篇文章: Apache Commons Lang StringUtils 常用方法詳解
Copyright ©
程式碼之家 All Rights Reserved