閱讀188 返回首頁    go 阿裏雲 go 技術社區[雲棲]


struts2中頁麵取值的原理以及valueStack的應用

 

一個簡單的用struts2標簽代碼獲取action中屬性的例子  

<table border="1" width="360">
   <caption>
    作者李剛的圖書
   </caption>
   <!-- 迭代輸出ValueStack中的books對象,其中status是迭代的序號 -->
  
 <s:iterator value="books" status="index">
    <s:if test="#index.odd == true">
     <tr >
    </s:if>
    <s:else>
     <tr>
    </s:else>
    <td>
     書名:
    </td>
    <td>
     <s:property />
    </td>
    </tr>
   
</s:iterator>
  </table>


Struts2將所有屬性值封裝在struts.valueStack請求屬性裏,可以通過request.getAttribute("struts.valueStack")獲取。Action所有的屬性都被封裝到了ValueStack對象中,它類似於map,Action中的屬性名可以理解為ValueStack中value的名字。可以通過valueStack.findValue("name")來取值。

 

 

BookService.java

public class BookService
{
 // 模擬數據庫
 private String[] books =
  new String[] {
   "瘋狂Java講義" ,
   "輕量級Java EE企業應用實戰",
   "瘋狂Ajax講義",
   "瘋狂XML講義",
   "Struts 2權威指南"
  };

 public String[] getLeeBooks()
 {
  return books;
 }


}

 


GetBooksAction.java

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

public class GetBooksAction implements Action
{
 private String[] books;

 public void setBooks(String[] books)
 {
  this.books = books;
 }

 public String[] getBooks()
 {
  return books;
 }

 public String execute() throws Exception
 {
  String user = (String)ActionContext.getContext().getSession().get("user");
  if (user != null && user.equals("crazyit"))
  {
   BookService bs = new BookService();
   setBooks(bs.getLeeBooks());
   return SUCCESS;
  }
  else
  {
   return LOGIN;
  }
 }
}

 


showBooks.jsp

<table border="1" width="360">

<%

// 獲取封裝輸出信息的ValueStack對象
ValueStack vs = (ValueStack)request.getAttribute("struts.valueStack");

// 調用ValueStack的fineValue方法獲取Action中的books屬性值
String[] books = (String[ ])vs.findValue("books");

//迭代輸出全部圖書信息
for (String book : books)
{
%>


<tr>
<td>書名:</td>
<td><%=book%></td>
</tr>

<%}%>


</table>

原帖地址:https://terryjs.iteye.com/blog/767699

 

 

最後更新:2017-04-02 16:48:03

  上一篇:go struts2中改變struts.xml默認路徑
  下一篇:go oracle中is null到底判斷的是什麼