Struts2 <s:submit> 標籤的 src 屬性必須包含專案根路徑(如 myroot/images/btn/btn_delete.jpg),一旦部署路徑變更,圖片即無法顯示。傳統解法 <%=request.getContextPath()%> 在 Struts2 標籤中無法直接使用。
${pageContext.request.contextPath},但強制需啟用 theme=ajax<input type="image"> + 命名慣例分析 <s:submit> 生成的 HTML 後,發現其核心功能(指定 Action 與 Method)可透過 name 屬性的特殊命名慣例實現:
<input type="image" alt="刪除指定用戶"
src="<%=request.getContextPath() %>/images/btn/btn_del.gif"
id="doDelete" name="action:user!doDelete"
class="button_image" onclick="return CheckSelectForDelete();" />
關鍵點:將 action 與 method 合併為 name="action:ActionName!methodName" 格式,Struts2 的預設處理機制會自動解析並路由至對應 Action 的方法。其他屬性(src、onclick、class 等)照常使用。
request.getContextPath() 或 JSTL <c:url> 生成正確相對路徑此方案簡單實用,適用於所有 Struts 2.x 版本,是處理圖片按鈕路徑問題的推薦做法。