原理:action向jsp頁面傳遞值時,如果在jsp頁面中是使用struts2標籤取值的話,那麼參數值會自動調用action中的參數getxxxxx()方法,將值自動取出後傳入jsp頁面中。如果在jsp頁面中是使用非struts2標籤取值的話,那麼將不會自動調用action中的參數getxxxxxx()方法,必須將參數放入session或request或applicaton中,然後再在jsp頁面中取值。
具體取值方法如下:
<1>.EL表達式:如 ${requestScope.username}
<2>、java代碼:<%request.getAttribute("username");%>
也有可能要使用<%request.getParameter("username");%>
<3>、使用ValueStack對象
<%
ValueStack vs = (ValueStack)request.getAttribute("struts.valueStack");
String username=(String)vs.findValue("username");
out.println(username);
%>
<4>、使用struts2自帶的標籤:
<s:property value="username"/>
注意:在從action向其他地方傳值時,在struts.xml配置文件中,要把action的result標籤裏的type值設爲dispatcher而不能使用redirect,否則傳值不能成功。
》redirect:action處理完後重定向到一個視圖資源(如:jsp頁面),請求參數全部丟失,action處理結果也全部丟失。 <result name="success" type="redirect">/displayCart.action?userId=${userId}</result>
2》redirect-action:action處理完後重定向到一個action,請求參數全部丟失,action處理結果也全部丟失。
重定向的調用者和被調用者使用各自的request and response對象,它們屬於兩個獨立的訪問請求和響應過程。
重定向需要兩次請求能完成的工作,請求轉發只要通過一次請求即可完成。這樣一來我們也就明白了爲什麼請求不會造成數據丟失。
<result name="success" type="redirect-action">/displayCart?userId=${userId}</result>
3》chain:action處理完後轉發到一個action,請求參數全部丟失,action處理結果不會丟失。
chain攔截器,處於chain鏈中的所有action共享一下值棧,每個action把值壓入值棧,要用值時從值棧中取