1. 程式人生 > >Struts2 之 Action類與 jsp 頁面的資料互動

Struts2 之 Action類與 jsp 頁面的資料互動

使用Struts2標籤,需要先在頁面中引入Struts2標籤庫:(標籤庫的位置在struts2-core-2.3.1.2.jar包中
<%@ taglib prefix="s"uri="/struts-tags" %>


* Action 類接收資料的三種方式

    1.使用Action屬性接收    2.使用DomainModel接收    3.使用ModelDriven接收 (推薦使用)


* Action 類返回資料的方式

用OGNL表示式顯示值棧中的資料的時候:

  • 如果要訪問物件棧中的值,直接訪問屬性即可。
  • 如果要訪問Map棧中的值,需要加#。

值棧(Map棧、物件棧)方式:

1.物件棧的操作

將物件放到棧頂:  ActionContext.getContext().getValueStack().push(user);
       頁面獲取方式:  <s:propertyvalue="username"/>

將物件放到棧頂:ActionContext.getContext().getValueStack().push("xxx");

       頁面獲取方式:   <s:property/>

將list存放到物件棧:ActionContext.getContext().getValueStack().push(userList);

頁面獲取方式:  
<s:iterator>
<s:propertyvalue="username"/>
<s:propertyvalue="userage"/>
</s:iterator>

   注:
           <s:propertory/>是一個輸出標籤:
           說明:如果不寫value屬性,則直接輸出棧頂元素。如果在物件棧中出現相同的元素,則會從上往下找,直到找到就停止了
2.Map棧的操作
把資料直接放到Map棧:ActionContext.getContext().put("a", "xxx");
         頁面獲取方式:<s:property
value="a"/> 或者 
${a}
把物件直接放到Map棧:ActionContext.getContext().put("a", user);

         頁面獲取方式:<s:propertyvalue="a.username"/> 或者 ${a.username}

將list存放到Map棧:ActionContext.getContext().put("userList"userList);
頁面獲取方式:<s:iterator value="#personList">
<s:propertyvalue="username"/>
<s:propertyvalue="userage"/>
</s:iterator>

把資料放到Request域:ServletActionContext.getRequest().setAttribute("a""xxx");
        頁面獲取方式:<s:propertyvalue="#request.a"/> 或者 ${requestScope.a}
把物件放到Request域:ServletActionContext.getRequest().setAttribute("a"user);
        頁面獲取方式:<s:propertyvalue="#request.a.username"/> 或者 ${requestScope.a.username}

把資料放到session域:ServletActionContext.getRequest().getSession().setAttribute("a""xx");
把資料放到Application域:ServletActionContext.getServletContext().setAttribute("a""xxx"); 

頁面獲取方式同Request域