1. 程式人生 > >Struts2-Action中獲取ServletAPI

Struts2-Action中獲取ServletAPI

struts2HttpServletRequestHttpSessionServletContext進行了封裝,
構造了三個Map物件來替代這三個物件。在action中獲取這三個物件的方法有
三種。
1、通過ActionContext獲取

        ActionContext ac = ActionContext.getContext();
        Map<String,Object> application = ac.getApplication();
        Map<String, Object> session = ac.getSession
(); ac.put("req", "req"); application.put("application", "application"); session.put("session", "session");

2、通過ServletActionContext獲取

        HttpServletRequest request = ServletActionContext.getRequest();
        request.setAttribute("req", "req");
        request.getSession
().setAttribute("session", "session"); request.getServletContext().setAttribute("application", "application");

3、通過實現SessionAware,ApplicationAware,RequestAware介面,在實現方法內賦值獲取

public class testAction  implements RequestAware,SessionAware,ApplicationAware{

    private Map<String, Object> request;
    private
Map<String, Object> session; private Map<String, Object> application; public String execute(){ System.out.println("struts"); request.put("req", "request"); application.put("application", "application"); session.put("session", "session"); return "success"; } @Override public void setApplication(Map<String, Object> application) { this.application = application; } @Override public void setSession(Map<String, Object> session) { this.session = session; } @Override public void setRequest(Map<String, Object> request) { this.request = request; } }

在action後的跳轉頁面檢測值

request = ${requestScope.req}<br>
session = ${sessionScope.session}<br>
application = ${applicationScope.application}<br>

這裡寫圖片描述