Struts2獲取request三種方法


struts2里面有三種方法可以獲取request,最好使用ServletRequestAware接口通過IOC機制注入Request對象。

在Action中獲取request方法一:

Action中的代碼:

Map request=(Map)ActionContext.getContext().get("request");

List<Task> Lasks = taskManager.findAll();

request.put("tasks",tasks);

 

在JSP頁面中獲取其中的值:

<s:iteratorid="task"value="#request.tasks">

<trclass="table_header">

<td><s:propertyvalue="#task.tname"/></td>

<td><s:propertyvalue="#task.tuid"/></td>

<td><s:propertyvalue="#task.tstartTime"/></td>

<td><s:propertyvalue="#task.tendTime"/></td>

<td><s:propertyvalue="#task.tstate"/></td>

<td><inputtype="radio"id="choose"name="choose"onclick="getId(this.value)"v

alue="<s:property value='#task.tid'/>"/></td>

</tr>

</s:iterator>

 

方法二:通過ServletActionContext類來獲取,使用struts2經驗如果處理get傳參是中文,只能使用該方法進行處理亂碼問題

Action中代碼:HttpServletRequest request = ServletActionContext.getRequest();

request.setAttribute("username","zhangsan");

在jsp中獲取其中的值

<s:propertyvalue="#request.username">或者${requestScope.req}

 

方法三:通過ServletRequestAware接口通過IOC機制注入Request對象

Action中的代碼:

Action實現ServletRequestAware接口,實現接口中的方法

privateHttpServletRequest request;

實現接口中的方法

publicvoidsetServletRequest(HttpServletRequest request){

this.request = request;

}

//然后在execute()方法中就可以使用了

publicString execute(){

request.setAttribute("username",

"zhangsan");

request.getSession().getServletContext().getApplication();

//得到Application

}

該方法必須要實現,而且該方法是自動被調用這個方法在被調用的過程中,會將創建好的request對象通過參數的方式傳遞給你,你可以用來賦給你本類中的變量,然后request就可以使用了

注意:

setServletRequest()方法一定會再execute()方法被調用前執行在jsp頁面中獲取其中的值

1<s:propertyvalue="#request.task.tname"/>

在上面的代碼中,在Action實現了一個ServletRequestAware接口,並且實現了setServletRequest方法。

如果一個動作類實現了ServletRequestAware接口,Struts2在調用execute方法之前,就會先調用setServletRequest方法,並將Request參數傳入這個方法。如果想獲得HttpServletResponse、HttpSession和Cookie等對象,動作類可以分別實現ServletResponseAware、SessionAware和CookiesAware等接口。這些接口都在org.apache.struts2.interceptor包中。

struts2超鏈接傳值:<s:a href="info.action?id=%{#list.id}"><s:propertyvalue="#list.title"/></s:a>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM