奠基 Struts 2 核心配置知識:常量載入優先級、package namespace 對應模組概念、Action 類型選擇、Servlet API 存取三種方式、動態方法調用兩種機制、method 屬性配置優缺點。
struts-default.xmlstruts-plugin.xmlstruts.xmlweb.xml強烈不建議在 web.xml 配置 Struts 2 常量。
Struts 1 ForwardAction → Struts 2:
<action name="Showcase">
<result>/showcase.jsp</result>
</action>
Showcase.action 直接映射 /showcase.jsp。
<package namespace="/book"> 相當於 Struts 1 模組,但切換更便利。Action GetBooks 需用 /book/GetBooks.action 映射。
"" → 預設命名空間(全域 Action,類似 Struts 1 <global-action>)"/" → 根命名空間,URL 為 /GetBooks.action系統不區分封裝請求參數的屬性與封裝處理結果的屬性,兩者完全平等。
Action 介面ActionSupport(預設處理類,未指定 class 時自動使用)ActionContext(推薦,解耦)操作 Map 實例,Struts 2 自動映射至真實 Servlet API:
ActionContext.getContext().getSession() → HttpSession attributesgetRequest()、getApplication() 同理get()/put() 針對 Request attributesHttpServletResponse 方法ServletContextAware、ServletRequestAware、ServletResponseAwaresetXxx() 方法獲取真實實例ServletActionContext 靜態方法(強耦合)直接獲取各 Servlet API 實例,讓 Action 與 Servlet API 耦合。
HttpServletResponse 的特殊說明即使獲取 HttpServletResponse,**不要在 Action 直接輸出響應**(無效果)。Action 僅為控制器,不直接生成響應。這就是 ActionContext 不提供 Response 操作的原因(僅操作 Cookie 需用到)。Struts 1 中 Action 返回 null 可用 response.getWriter().println() 輸出,Struts 2 不可。
action="ActionName!methodName.action"<form action="Login!regist.action"> → 呼叫 LoginAction.regist() 而非 execute()
一個 Action 可包含多邏輯,無需配置檔額外設定,比 Struts 1 更便利。
method 屬性<action name="Login" class="com.unmi.LoginAction" method="regist">
同樣一個 Action 類定義多邏輯,每個映射成邏輯 Action。缺點:
<result> 配置class 屬性值產生冗余