引用:http://qsfwy.iteye.com/blog/682796
Struts2+JQuery+JSON实现异步交互,包括从后台获得单个值、对象、List和Map数据并从前台的表达中获取值把值进行序列化通过JQuery的$.ajax({})传到后台和后台的对象进行绑定。
第一步:在MyEclipse中创建JavaWeb工厂并把Struts2 和 json的jar包添加到工程中添加完成后的工程图是:
第二步:创建后台:
1. UserInfo实体类:
- package struts2jsonjquery.test.entity;
- import java.io.Serializable;
- /**
- * <p>
- * 用户实体类
- * </p>
- * @author 朱延伟
- *
- */
- public class UserInfo implements Serializable {
- private static final long serialVersionUID = 3952189513312630860L;
- private int userId;
- private String userName;
- private String password;
- public int getUserId() {
- return userId;
- }
- public void setUserId(int userId) {
- this.userId = userId;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
- package struts2jsonjquery.test.entity;
- import java.io.Serializable;
- /**
- * <p>
- * 用户实体类
- * </p>
- * @author 朱延伟
- *
- */
- public class UserInfo implements Serializable {
- private static final long serialVersionUID = 3952189513312630860L;
- private int userId;
- private String userName;
- private String password;
- public int getUserId() {
- return userId;
- }
- public void setUserId(int userId) {
- this.userId = userId;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
2. Action类
- package struts2jsonjquery.test.action;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import struts2jsonjquery.test.entity.UserInfo;
- import com.opensymphony.xwork2.ActionSupport;
- public class JsonJqueryStruts2Action extends ActionSupport {
- private static final long serialVersionUID = 3518833679938898354L;
- private String message; //使用json返回单个值
- private UserInfo userInfo; //使用json返回对象
- private List<UserInfo> userInfosList; //使用josn返回List对象
- private Map<String,UserInfo> userInfosMap; //使用json返回Map对象
- //为上面的的属性提供get,Set方法
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- public UserInfo getUserInfo() {
- return userInfo;
- }
- public void setUserInfo(UserInfo userInfo) {
- this.userInfo = userInfo;
- }
- public List<UserInfo> getUserInfosList() {
- return userInfosList;
- }
- public void setUserInfosList(List<UserInfo> userInfosList) {
- this.userInfosList = userInfosList;
- }
- public Map<String, UserInfo> getUserInfosMap() {
- return userInfosMap;
- }
- public void setUserInfosMap(Map<String, UserInfo> userInfosMap) {
- this.userInfosMap = userInfosMap;
- }
- /**
- * <p>
- * 返回单个值
- * <p>
- * @return
- */
- public String returnMessage(){
- this.message = "成功返回单个值";
- return "message";
- }
- /**
- * <p>
- * 返回UserInfo对象
- * </p>
- * @return
- */
- public String returnUserInfo(){
- userInfo = new UserInfo();
- userInfo.setUserId(10000);
- userInfo.setUserName("张三");
- userInfo.setPassword("000000");
- return "userInfo";
- }
- /**
- * <p>
- * 返回List对象
- * </p>
- * @return
- */
- public String returnList(){
- userInfosList = new ArrayList<UserInfo>();
- UserInfo u1 = new UserInfo();
- u1.setUserId(10000);
- u1.setUserName("张三");
- u1.setPassword("000000");
- UserInfo u2 = new UserInfo();
- u2.setUserId(10001);
- u2.setUserName("李四");
- u2.setPassword("111111");
- UserInfo u3 = new UserInfo();
- u3.setUserId(10002);
- u3.setUserName("王五");
- u3.setPassword("222222");
- UserInfo u4 = new UserInfo();
- u4.setUserId(10003);
- u4.setUserName("赵六");
- u4.setPassword("333333");
- userInfosList.add(u1);
- userInfosList.add(u2);
- userInfosList.add(u3);
- userInfosList.add(u4);
- return "list";
- }
- /**
- * <p>
- * 返回Map对象
- * </p>
- * @return
- */
- public String returnMap(){
- userInfosMap = new HashMap<String,UserInfo>();
- UserInfo u1 = new UserInfo();
- u1.setUserId(10000);
- u1.setUserName("张三");
- u1.setPassword("000000");
- UserInfo u2 = new UserInfo();
- u2.setUserId(10001);
- u2.setUserName("李四");
- u2.setPassword("111111");
- UserInfo u3 = new UserInfo();
- u3.setUserId(10002);
- u3.setUserName("王五");
- u3.setPassword("222222");
- UserInfo u4 = new UserInfo();
- u4.setUserId(10003);
- u4.setUserName("赵六");
- u4.setPassword("333333");
- userInfosMap.put(u1.getUserId()+"", u1);
- userInfosMap.put(u2.getUserId()+"", u2);
- userInfosMap.put(u3.getUserId()+"", u3);
- userInfosMap.put(u4.getUserId()+"", u4);
- return "map";
- }
- /**
- * <p>
- * 获得对象,也就是通过表达获得对象(异步的)
- * </P>
- * @return
- */
- public String gainUserInfo(){
- System.out.println("用户ID:"+userInfo.getUserId());
- System.out.println("用户名:"+userInfo.getUserName());
- System.out.println("密码:"+userInfo.getPassword());
- return "userInfo";
- }
- /**
- * 获得单个值就不用写了和平常一样
- */
- }
- package struts2jsonjquery.test.action;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import struts2jsonjquery.test.entity.UserInfo;
- import com.opensymphony.xwork2.ActionSupport;
- public class JsonJqueryStruts2Action extends ActionSupport {
- private static final long serialVersionUID = 3518833679938898354L;
- private String message; //使用json返回单个值
- private UserInfo userInfo; //使用json返回对象
- private List<UserInfo> userInfosList; //使用josn返回List对象
- private Map<String,UserInfo> userInfosMap; //使用json返回Map对象
- //为上面的的属性提供get,Set方法
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- public UserInfo getUserInfo() {
- return userInfo;
- }
- public void setUserInfo(UserInfo userInfo) {
- this.userInfo = userInfo;
- }
- public List<UserInfo> getUserInfosList() {
- return userInfosList;
- }
- public void setUserInfosList(List<UserInfo> userInfosList) {
- this.userInfosList = userInfosList;
- }
- public Map<String, UserInfo> getUserInfosMap() {
- return userInfosMap;
- }
- public void setUserInfosMap(Map<String, UserInfo> userInfosMap) {
- this.userInfosMap = userInfosMap;
- }
- /**
- * <p>
- * 返回单个值
- * <p>
- * @return
- */
- public String returnMessage(){
- this.message = "成功返回单个值";
- return "message";
- }
- /**
- * <p>
- * 返回UserInfo对象
- * </p>
- * @return
- */
- public String returnUserInfo(){
- userInfo = new UserInfo();
- userInfo.setUserId(10000);
- userInfo.setUserName("张三");
- userInfo.setPassword("000000");
- return "userInfo";
- }
- /**
- * <p>
- * 返回List对象
- * </p>
- * @return
- */
- public String returnList(){
- userInfosList = new ArrayList<UserInfo>();
- UserInfo u1 = new UserInfo();
- u1.setUserId(10000);
- u1.setUserName("张三");
- u1.setPassword("000000");
- UserInfo u2 = new UserInfo();
- u2.setUserId(10001);
- u2.setUserName("李四");
- u2.setPassword("111111");
- UserInfo u3 = new UserInfo();
- u3.setUserId(10002);
- u3.setUserName("王五");
- u3.setPassword("222222");
- UserInfo u4 = new UserInfo();
- u4.setUserId(10003);
- u4.setUserName("赵六");
- u4.setPassword("333333");
- userInfosList.add(u1);
- userInfosList.add(u2);
- userInfosList.add(u3);
- userInfosList.add(u4);
- return "list";
- }
- /**
- * <p>
- * 返回Map对象
- * </p>
- * @return
- */
- public String returnMap(){
- userInfosMap = new HashMap<String,UserInfo>();
- UserInfo u1 = new UserInfo();
- u1.setUserId(10000);
- u1.setUserName("张三");
- u1.setPassword("000000");
- UserInfo u2 = new UserInfo();
- u2.setUserId(10001);
- u2.setUserName("李四");
- u2.setPassword("111111");
- UserInfo u3 = new UserInfo();
- u3.setUserId(10002);
- u3.setUserName("王五");
- u3.setPassword("222222");
- UserInfo u4 = new UserInfo();
- u4.setUserId(10003);
- u4.setUserName("赵六");
- u4.setPassword("333333");
- userInfosMap.put(u1.getUserId()+"", u1);
- userInfosMap.put(u2.getUserId()+"", u2);
- userInfosMap.put(u3.getUserId()+"", u3);
- userInfosMap.put(u4.getUserId()+"", u4);
- return "map";
- }
- /**
- * <p>
- * 获得对象,也就是通过表达获得对象(异步的)
- * </P>
- * @return
- */
- public String gainUserInfo(){
- System.out.println("用户ID:"+userInfo.getUserId());
- System.out.println("用户名:"+userInfo.getUserName());
- System.out.println("密码:"+userInfo.getPassword());
- return "userInfo";
- }
- /**
- * 获得单个值就不用写了和平常一样
- */
- }
3. struts.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <package name="default" namespace="/" extends="json-default">
- <action name="jsontest" class="struts2jsonjquery.test.action.JsonJqueryStruts2Action">
- <!-- 返回单个值的result -->
- <result name="message" type="json"></result>
- <!-- 返回UserInfo对象的 -->
- <result name="userInfo" type="json"></result>
- <!-- 返回List对象的 -->
- <result name="list" type="json"></result>
- <!-- 返回Map对象的 -->
- <result name="map" type="json"></result>
- </action>
- </package>
- </struts>
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <package name="default" namespace="/" extends="json-default">
- <action name="jsontest" class="struts2jsonjquery.test.action.JsonJqueryStruts2Action">
- <!-- 返回单个值的result -->
- <result name="message" type="json"></result>
- <!-- 返回UserInfo对象的 -->
- <result name="userInfo" type="json"></result>
- <!-- 返回List对象的 -->
- <result name="list" type="json"></result>
- <!-- 返回Map对象的 -->
- <result name="map" type="json"></result>
- </action>
- </package>
- </struts>
前台:
1. index.jsp
- <%@ page language="java" pageEncoding="GBK"%>
- <%
- String path = request.getContextPath();
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Struts2+JQuery+JSON</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">
- <script type="text/javascript" src="<%=path %>/js/jquery.js"></script>
- <script type="text/javascript" src="<%=path %>/js/json.js"></script>
- </head>
- <body>
- <input id="getMessage" type="button" value="获取单个值"/>
- <input id="getUserInfo" type="button" value="获取UserInfo对象"/>
- <input id="getList" type="button" value="获取List对象"/>
- <input id="getMap" type="button" value="获取Map对象"/>
- <br>
- <br>
- <br>
- <!-- 要显示信息的层 -->
- <div id="message"></div>
- <form>
- 用户ID:<input name="userInfo.userId" type="text"/><br/>
- 用户名:<input name="userInfo.userName" type="text"/><br/>
- 密 码:<input name="userInfo.password" type="text"/><br>
- <input id="regRe" type="button" value="注册"/>
- </form>
- </body>
- </html>
- <%@ page language="java" pageEncoding="GBK"%>
- <%
- String path = request.getContextPath();
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Struts2+JQuery+JSON</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">
- <script type="text/javascript" src="<%=path %>/js/jquery.js"></script>
- <script type="text/javascript" src="<%=path %>/js/json.js"></script>
- </head>
- <body>
- <input id="getMessage" type="button" value="获取单个值"/>
- <input id="getUserInfo" type="button" value="获取UserInfo对象"/>
- <input id="getList" type="button" value="获取List对象"/>
- <input id="getMap" type="button" value="获取Map对象"/>
- <br>
- <br>
- <br>
- <!-- 要显示信息的层 -->
- <div id="message"></div>
- <form>
- 用户ID:<input name="userInfo.userId" type="text"/><br/>
- 用户名:<input name="userInfo.userName" type="text"/><br/>
- 密 码:<input name="userInfo.password" type="text"/><br>
- <input id="regRe" type="button" value="注册"/>
- </form>
- </body>
- </html>
2. json.js
- //初始加载页面时
- $(document).ready(function(){
- //为获取单个值的按钮注册鼠标单击事件
- $("#getMessage").click(function(){
- $.getJSON("jsontest!returnMessage.action",function(data){
- //通过.操作符可以从data.message中获得Action中message的值
- $("#message").html("<font color='red'>"+data.message+"</font>");
- });
- });
- //为获取UserInfo对象按钮添加鼠标单击事件
- $("#getUserInfo").click(function(){
- $.getJSON("jsontest!returnUserInfo.action",function(data){
- //清空显示层中的数据
- $("#message").html("");
- //为显示层添加获取到的数据
- //获取对象的数据用data.userInfo.属性
- $("#message").append("<div><font color='red'>用户ID:"+data.userInfo.userId+"</font></div>")
- .append("<div><font color='red'>用户名:"+data.userInfo.userName+"</font></div>")
- .append("<div><font color='red'>密码:"+data.userInfo.password+"</font></div>")
- });
- });
- //为获取List对象按钮添加鼠标单击事件
- $("#getList").click(function(){
- $.getJSON("jsontest!returnList.action",function(data){
- //清空显示层中的数据
- $("#message").html("");
- //使用jQuery中的each(data,function(){});函数
- //从data.userInfosList获取UserInfo对象放入value之中
- $.each(data.userInfosList,function(i,value){
- $("#message").append("<div>第"+(i+1)+"个用户:</div>")
- .append("<div><font color='red'>用户ID:"+value.userId+"</font></div>")
- .append("<div><font color='red'>用户名:"+value.userName+"</font></div>")
- .append("<div><font color='red'>密码:"+value.password+"</font></div>");
- });
- });
- });
- //为获取Map对象按钮添加鼠标单击事件
- $("#getMap").click(function(){
- $.getJSON("jsontest!returnMap.action",function(data){
- //清空显示层中的数据
- $("#message").html("");
- //使用jQuery中的each(data,function(){});函数
- //从data.userInfosList获取UserInfo对象放入value之中
- //key值为Map的键值
- $.each(data.userInfosMap,function(key,value){
- $("#message").append("<div><font color='red'>用户ID:"+value.userId+"</font></div>")
- .append("<div><font color='red'>用户名:"+value.userName+"</font></div>")
- .append("<div><font color='red'>密码:"+value.password+"</font></div>");
- });
- });
- });
- //向服务器发送表达数据
- $("#regRe").click(function(){
- //把表单的数据进行序列化
- var params = $("form").serialize();
- //使用jQuery中的$.ajax({});Ajax方法
- $.ajax({
- url:"jsontest!gainUserInfo.action",
- type:"POST",
- data:params,
- dataType:"json",
- success:function(data){
- //清空显示层中的数据
- $("#message").html("");
- //为显示层添加获取到的数据
- //获取对象的数据用data.userInfo.属性
- $("#message").append("<div><font color='red'>用户ID:"+data.userInfo.userId+"</font></div>")
- .append("<div><font color='red'>用户名:"+data.userInfo.userName+"</font></div>")
- .append("<div><font color='red'>密码:"+data.userInfo.password+"</font></div>")
- }
- });
- });
- });
- //初始加载页面时
- $(document).ready(function(){
- //为获取单个值的按钮注册鼠标单击事件
- $("#getMessage").click(function(){
- $.getJSON("jsontest!returnMessage.action",function(data){
- //通过.操作符可以从data.message中获得Action中message的值
- $("#message").html("<font color='red'>"+data.message+"</font>");
- });
- });
- //为获取UserInfo对象按钮添加鼠标单击事件
- $("#getUserInfo").click(function(){
- $.getJSON("jsontest!returnUserInfo.action",function(data){
- //清空显示层中的数据
- $("#message").html("");
- //为显示层添加获取到的数据
- //获取对象的数据用data.userInfo.属性
- $("#message").append("<div><font color='red'>用户ID:"+data.userInfo.userId+"</font></div>")
- .append("<div><font color='red'>用户名:"+data.userInfo.userName+"</font></div>")
- .append("<div><font color='red'>密码:"+data.userInfo.password+"</font></div>")
- });
- });
- //为获取List对象按钮添加鼠标单击事件
- $("#getList").click(function(){
- $.getJSON("jsontest!returnList.action",function(data){
- //清空显示层中的数据
- $("#message").html("");
- //使用jQuery中的each(data,function(){});函数
- //从data.userInfosList获取UserInfo对象放入value之中
- $.each(data.userInfosList,function(i,value){
- $("#message").append("<div>第"+(i+1)+"个用户:</div>")
- .append("<div><font color='red'>用户ID:"+value.userId+"</font></div>")
- .append("<div><font color='red'>用户名:"+value.userName+"</font></div>")
- .append("<div><font color='red'>密码:"+value.password+"</font></div>");
- });
- });
- });
- //为获取Map对象按钮添加鼠标单击事件
- $("#getMap").click(function(){
- $.getJSON("jsontest!returnMap.action",function(data){
- //清空显示层中的数据
- $("#message").html("");
- //使用jQuery中的each(data,function(){});函数
- //从data.userInfosList获取UserInfo对象放入value之中
- //key值为Map的键值
- $.each(data.userInfosMap,function(key,value){
- $("#message").append("<div><font color='red'>用户ID:"+value.userId+"</font></div>")
- .append("<div><font color='red'>用户名:"+value.userName+"</font></div>")
- .append("<div><font color='red'>密码:"+value.password+"</font></div>");
- });
- });
- });
- //向服务器发送表达数据
- $("#regRe").click(function(){
- //把表单的数据进行序列化
- var params = $("form").serialize();
- //使用jQuery中的$.ajax({});Ajax方法
- $.ajax({
- url:"jsontest!gainUserInfo.action",
- type:"POST",
- data:params,
- dataType:"json",
- success:function(data){
- //清空显示层中的数据
- $("#message").html("");
- //为显示层添加获取到的数据
- //获取对象的数据用data.userInfo.属性
- $("#message").append("<div><font color='red'>用户ID:"+data.userInfo.userId+"</font></div>")
- .append("<div><font color='red'>用户名:"+data.userInfo.userName+"</font></div>")
- .append("<div><font color='red'>密码:"+data.userInfo.password+"</font></div>")
- }
- });
- });
- });
注意:JSON插件会把所有包含getter方法的属性都序列化到返回结果中,所以Action中的其他execute方法都不要把名
字加get前缀。
可以下载工程文件