<%@ page language="java" contentType="text/html; charset=GBK"%><!-- 導入Struts 2的標簽庫 --><%@taglib prefix="s" uri="/struts-tags"%><html> <head> <title>作者李剛的圖書</title> </head> <body> <table border="1" width="360"> <caption> 作者李剛的圖書 </caption> <!-- 迭代輸出ValueStack中的books對象,其中status是迭代的序號 --> <s:iterator value="books" status="index"> <!-- 判斷序號是否為奇數 --> <s:if test="#index.odd == true"> <tr style="background-color: #cccccc"> </s:if> <!-- 判斷迭代元素的序號是否不為偶數 --> <s:else> <tr> </s:else> <td> 書名: </td> <td> <s:property /> </td> </tr> </s:iterator> </table> </body> </html>
?Struts 2將所有屬性值封裝在struts.valueStack請求屬性里,可以通過
request
.getAttribute("struts.valueStack")獲取。Action所有的屬性都被封裝到了ValueStack對象中,它類似于map,Action中的屬性名可以理解為ValueStack中value的名字。
? 可以通過valueStack.findValue("name")來取值
?
?
public class BookService{ //以一個常量數組模擬了從持久存儲設備(數據庫)中取出的數據 private String[] books = new String[]{"Spring2.0寶典" ,"輕量級J2EE企業應用實戰","基于J2EE的Ajax寶典","Struts,Spring,Hibernate整合開發"}; //業務邏輯方法,該方法返回全部圖書public String[] getLeeBooks(){return books; } }
?
public class GetBooksAction implements Action{ //該屬性并不用于封裝用戶請求參數,而用于封裝Action需要輸出到JSP頁面信息private String[] books; //books屬性的setter方法 public void setBooks(String[] books){ this.books = books; } //books屬性的getter方法 public String[] getBooks(){ return books; } //處理用戶請求的execute方法 public String execute() throws Exception{ //獲取Session中的user屬性 String user = (String)ActionContext.getContext().getSession().get("user"); //如果user屬性不為空,且該屬性值為scott if (user != null && user.equals("scott")){ //創建BookService實例 BookService bs = new BookService(); //將業務邏輯組件的返回值設置成該Action的屬性 setBooks(bs.getLeeBooks()); return SUCCESS; }else{ return LOGIN; } } }
?
<%@ page language="java" contentType="text/html; charset=GBK"><% @page import="java.util.*,com.opensymphony.xwork2.util.*"%> <html> <head> <title>作者李剛的圖書</title> </head> <body> <table border="1" width="360"> <caption>作者李剛的圖書</caption> <%//獲取封裝輸出信息的ValueStack對象 ValueStack vs = (ValueStack)request.getAttribut("struts.valueStack"); //調用ValueStack的fineValue方法獲取Action中的books屬性值 String[] books = (String[])vs.findValue("books"); //迭代輸出全部圖書信息 for (String book : books){ %> <tr> <td>書名:</td> <td><%=book%></td> </tr> <%}%> </table> </body> </html>
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
