-----------------------------------------------------------------------------------------jsp------------------------------------------------------------------------------------------------------------
<title>查看所有商品</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
$("#a").toggle(function(){
//向服务器发送请求
$.post("/struts2.0/showProduct",function(data){
//把响应回来的json转换成html代码,展示在div中
var html="<table border=‘1‘><tr><td>商品编号</td><td>商品名称</td><td>商品价格</td></tr>";
for (var i= 0; i < data.length; i++) {
html+="<tr><td>"+data[i].id+"</td><td>"+data[i].name+"</td><td>"+data[i].price+"</td></tr>";
}
html+="</table>";
$("#productMsg").html(html);
},"json");
},function(){
$("#productMsg").html("");
});
});
</script>
</head>
<body>
<!-- 空链接 --><a href="javascript:void(0)" id="a">查看所有商品</a>
<div id="productMsg"></div>
</body>
</html>
----------------------------------------------------------------------------------------action------------------------------------------------------------------------------------------------------------
public class ProductAction {
public String check(){
Product p1 = new Product();
p1.setId(1);
p1.setName("电视机");
p1.setPrice(2000);
Product p2 = new Product();
p2.setId(2);
p2.setName("电冰箱");
p2.setPrice(3000);
List<Product> list = new ArrayList<Product>();
list.add(p1);
list.add(p2);
ValueStack valueStack = ActionContext.getContext().getValueStack();
//将List<Product>压入valueStack栈顶中,在struts-xml设置了<package extends=”json-default”>.
//Action的返回视图<result name=””type=”json”>,那么struts2框架就会将valueStack中的栈顶元素转换成json响应到浏览器
valueStack.push(list);
return "success";