`

struts2中页面取值的原理

阅读更多
<%@ 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>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics