struts2学习笔记--使用struts2插件实现ajax处理(返回json数据)
贴一个简单的例子,通过jquery的post调用action,定义一个对象User,有name和age属性,实例化几个对象,以json的格式返回到jsp,在前台页面显示出来,模拟用户列表.
- 导入相关jar包:
- ezmorph-1.0.6.jar
- json-lib-2.3-jdk15.jar
- struts2-json-plugin-2.3.16.1.jar
- Action代码:
package com.wang.action;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.Action;
import com.wang.entity.User;
import net.sf.json.JSONArray;
public class JsonAction {
private JSONArray root;
public String execute(){
List<User> list=new ArrayList<User>();
list.add(new User("wang",20));
list.add(new User("yong",22));
list.add(new User("guo",23));
root=JSONArray.fromObject(list);
System.out.println("json="+root.toString());
return Action.SUCCESS;
}
public JSONArray getRoot() {
return root;
}
public void setRoot(JSONArray root) {
this.root = root;
}
}
- jsp页面:
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'ajax.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#btn1').click(function(){
$.post("json.action",function(data){
var html="";
for(var i=0;i<data.length;i++){
html+="<tr><td>"+data[i].name+"</td><td>"+data[i].age+"</td></tr>";
}
$('#content').html(html);
});
});
$('#btn2').click(function(){
// alert("a");
$('#content').css("display","none");
});
});
</script>
</head>
<body>
<input type="button" name="btn" id="btn1" value="获取json"/><br>
<table width="80%" align="center">
<tr>
<td>姓名</td>
<td>年龄</td>
</tr>
<tbody id="content">
</tbody>
</table>
<input type="button" name="btn" id="btn2" value="隐藏json信息"/><br>
</body>
</html>
- struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<!--注意这里继承的json-default,间接地也继承struts-default-->
<package name="default" extends="json-default" namespace="/">
<action name="json" class="com.wang.action.JsonAction">
<result type="json">
<param name="root">root</param>
</result>
</action>
</package>
</struts>