Struts 擴展 JSP 標準標籤庫,提供六大標籤庫,覆蓋數據訪問、表單生成、邏輯控制、佈局模板、頁面組合、嵌套增強。
| 標籤庫 URI (前綴) | 核心功能 | 代表標籤 |
|---|---|---|
struts-bean (bean:) | Bean 訪問、屬性輸出、消息國際化、Cookie/Header 讀取、頁面上下文變量定義 | <bean:write>, <bean:message>, <bean:define>, <bean:cookie> |
struts-html (html:) | 表單生成、輸入控件、鏈接重寫、圖片、JavaScript 驗證集成、Base 標籤 | <html:form>, <html:text>, <html:link>, <html:rewrite>, <html:javascript> |
struts-logic (logic:) | 條件輸出、迭代、比較、重定向、為空/不為空判斷、消息存在性檢查 | <logic:iterate>, <logic:equal>, <logic:present>, <logic:redirect> |
struts-template (template:) | 模板機制:定義模板、插入參數、組合頁面 (被 Tiles 取代) | <template:put>, <template:insert>, <template:get> |
struts-tiles (tiles:) | 強大佈局框架:定義佈局、組合頁面、動態屬性、控制器綁定、定義繼承 | <tiles:insert>, <tiles:definition>, <tiles:putAttribute>, <tiles:importAttribute> |
struts-nested (nested:) | 巢狀上下文支援:讓上述標籤在巢狀 Bean 結構中相對路徑訪問屬性 | <nested:write>, <nested:iterate>, <nested:root> |
問題:<a href="/> 跳轉至域名根而非上下文根。
解決:<html:link page="/welcome.do">Home</html:link> 自動添加上下文路徑,生成 /myapp/welcome.do。同理 <html:rewrite>、<html:form action="/login.do">。
ApplicationResources.properties、ApplicationResources_zh_CN.properties。struts-config.xml 配置:<message-resources parameter="ApplicationResources"/>。<bean:message key="welcome.title"/>、<html:errors/> 自動顯示校驗錯誤信息。getResources(request).getMessage("key")。<tiles:definition name="baseLayout" template="/layout.jsp">
<tiles:putAttribute name="header" value="/header.jsp"/>
<tiles:putAttribute name="menu" value="/menu.jsp"/>
<tiles:putAttribute name="body" value="/body.jsp"/>
<tiles:putAttribute name="footer" value="/footer.jsp"/>
</tiles:definition>
<!-- 頁面繼承佈局,僅覆蓋 body -->
<tiles:definition name="userList" extends="baseLayout">
<tiles:putAttribute name="body" value="/user/list.jsp"/>
</tiles:definition>
<tiles:putAttribute name="title" value="User List" type="string"/>。<tiles:definition name="userList" controllerClass="com.web.UserListController"/>,預備數據供佈局內 JSP 使用。<forward name="success" path="tiles.userList"/>,path 對應 Tiles 定義名,減少物理 JSP 文件數量。org.apache.struts.action.ExceptionHandler:設置 ActionError (來自 key)、轉發至 path。
ExceptionHandler,覆寫 execute(Exception, ExceptionConfig, ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse)。struts-config.xml 註冊:<global-exceptions>
<exception
handler="com.app.struts.CustomExceptionHandler"
key="global.error.message"
path="/error.jsp"
scope="request"
type="java.lang.Exception"/>
</global-exceptions>
Taglib 消除 Scriptlet,Tiles 實現佈局復用與動態組合,I18N 內建支援全球化,異常處理聲明式配置 + 自定義擴展滿足企業級需求。這套生態讓 Struts 1.x 時代的 JSP 開發高效、規範、可維護。