在Struts2中,除了透過Aware介面注入物件外,也可以使用非IoC方式直接取得request、response與session。這在除錯或特定工具方法中很常見。
HttpServletRequest req1 = ServletActionContext.getRequest();
HttpServletRequest req2 = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
HttpServletRequest req3 = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
這些寫法最終都會走到相同的上下文取值邏輯,因為ServletActionContext繼承了ActionContext,相關常數也對應同一個字串鍵值。
HttpServletResponse res1 = ServletActionContext.getResponse();
HttpServletResponse res2 = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
先取得request,再呼叫:
HttpSession session = request.getSession();
理解這些API的底層來源,有助於在複雜框架環境中快速定位問題。