ActionContext.getContext().put()理由:ActionContext 為 ThreadLocal,單元測試困難、耦合 Struts 內部、不利遷移。
public class UserAction extends ActionSupport {
private List<UserVO> userList = new ArrayList<>(); // 必須初始化
public List<UserVO> getUserList() { return userList; }
public void setUserList(List<UserVO> userList) { this.userList = userList; }
public String execute() {
userList = userService.queryAll(); // 業務查詢
return SUCCESS;
}
}
JSP 直接用 OGNL 存取:。
public String execute() {
List<UserVO> list = userService.queryAll();
ServletActionContext.getRequest().setAttribute("userList", list); // 標準 Servlet API
return SUCCESS;
}
JSP 用 ${userList} 或 。
| 維度 | 屬性驅動 | 請求屬性 |
|---|---|---|
| 型別安全 | 高(編譯期檢查 getter/setter) | 低(運行期 Map 查找) |
| 單元測試 | 易(直接 new Action 呼叫 getter) | 需模擬 Request |
| Struts 耦合度 | 低(僅繼承 ActionSupport) | 低(使用標準 Servlet API) |
| 適用場景 | 主要業務資料、表單回填 | 臨時資料、跨 Action 轉發、攔截器共享 |
主要業務資料(列表、表單物件)用屬性驅動;臨時、跨請求共享資料用請求屬性。兩者均符合公司規範,避免 ActionContext。