struts2獲得ServletContext 的方法

來源:互聯網
上載者:User

http://blog.sina.com.cn/s/blog_61feef0c0100qdzu.html

Struts2擷取request三種方法

struts2裡面有三種方法可以擷取request,最好使用ServletRequestAware介面通過IOC機制注入Request對象。
在Action中擷取request方法一:
 
在Action中的代碼:
Map request = (Map)ActionContext.getContext().get("request");
List<Task> tasks = taskManager.findAll();
request.put("tasks", tasks);

方法二:通過ServletActionContext類來擷取,使用struts2經驗如果處理get傳參是中文,只能使用該方法進行處理亂碼問題
 
Action中代碼:
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("username", "zhangsan");

方法三:通過ServletRequestAware介面通過IOC機制注入Request對象
Action中的代碼:
Action實現ServletRequestAware介面,實現介面中的方法
     private HttpServletRequest request;
     //實現介面中的方法
     public void setServletRequest(HttpServletRequest request){
      this.request = request;
     }
     //然後在execute()方法中就可以使用了
     public String execute(){
      request.setAttribute("username", "zhangsan");
      request.getSession().getServletContext().getApplication(); //得到Application
     }
     該方法必須要實現,而且該方法是自動被調用
     這個方法在被調用的過程中,會將建立好的request對象通過參數的方式傳遞給你,你可以用來賦給你本類中的變數,然後request就可以使用了
     注意:setServletRequest()方法一定會再execute()方法被調用前執行

Struts2擷取request三種方法,當然也是獲得ServletContext的方法,這樣我們就可以獲得檔案夾的路徑了,但是  


ServletActionContext.getRequest();這種方法獲得的request在獲得ServletContext時會有問題,不信你就反覆重新整理

頁面,這個的方法絕對會報null 指標異常!!!


建議使用第三種方法,這個在反覆重新整理的情況下不會出現null 指標異常。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.