1. 程式人生 > >struts2 - View頁面中獲取Action的成員變數

struts2 - View頁面中獲取Action的成員變數

struts2 - View頁面中獲取Action的成員變數

2016年03月02日 11:04:44 閱讀數:1074   View頁面中獲取Action的成員變數

按照Struts的設計,在Action處理完後,把結果資料儲存在自己的成員變數裡,然後跳至result指定的頁面(VIEW頁面)。
VIEW頁面負責展現處理結果,那VIEW中如何獲取Action的資料呢?

方法一:Struts2 Property Tag / OGNL
http://struts.apache.org/2.x/docs/using-struts-2-tags.html


http://www.vaannila.com/struts-2/struts-2-example/struts-2-ognl-expression-language-example-1.html

 


比如,在Action裡有一個成員變數helloCount及其對應的getter
private int helloCount = 0;
 
public int getHelloCount() {
 return helloCount;
}

public void setHelloCount(int helloCount) {
 HelloWorldAction.helloCount = helloCount;
}

則在VIEW.jsp中,
宣佈使用struts的tag
    <%@ taglib prefix="s" uri="/struts-tags" %>
可以使用下面的tag來顯示helloCount的值:
     I've said hello <s:property value="helloCount" />

方法二: HttpRequest的getAttribute方法
實際上, 在Action處理完之後,跳到result頁面之前,struts應用把Action物件的成員變數放到了request的屬性裡(機制未知)
所以,可以用request物件來獲取Action的成員變數。
【似乎只能獲取Object,不能獲取int這種變數】

<%
           String username = (String) request.getAttribute("username");
%>