Struts2+JQuery,json数据格式请求响应

[1]model

日期类型需要装换,setBirthday中的@JSON(format="yyyy-MM-dd")规定前台页面输入日期格式为yyyy-MM-dd.

用户类

import java.util.Date;
import org.apache.struts2.json.annotations.JSON;

/**
 * 类名: User.java<br />
 * 类描述:用户
 * @version: 1.0
 * @date: 2013-4-6 下午6:43:44
 * **/
public class User {
	private Integer userId;
	private String username;
	private Date birthday;
	private Parents parents;
	
	public Integer getUserId() {
		return userId;
	}
	public String getUsername() {
		return username;
	}
	public Date getBirthday() {
		return birthday;
	}
	public Parents getParents() {
		return parents;
	}
	public void setUserId(Integer userId) {
		this.userId = userId;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	@JSON(format="yyyy-MM-dd")
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public void setParents(Parents parents) {
		this.parents = parents;
	}
}

用户类中的双亲类

/**
 * 类名: Parents.java<br />
 * 类描述:双亲
 * @version: 1.0
 * @date: 2013-4-6 下午7:10:26
 * **/
public class Parents {
	private String falther;
	private String mother;
	
	
	public String getFalther() {
		return falther;
	}
	public String getMother() {
		return mother;
	}
	public void setFalther(String falther) {
		this.falther = falther;
	}
	public void setMother(String mother) {
		this.mother = mother;
	}
}

调用到的Action.

使用json格式对应User类向服务端传输数据,之后使用json格式向客户端发出响应.

public class AddUserAction extends ActionSupport {
	private User user;
	/** result: 表示操作是否成功 **/
	private Boolean result;
	
	/** 方法描述:set方法,客户端->服务端	**/
	public void setUser(User user) {
		this.user = user;
	}
	/** 方法描述:get方法,服务端->客户端	**/
	public Boolean getResult() {
		return result;
	}

	@Override
	public String execute() throws Exception {
		System.out.println("用户名:" + user.getUsername() + 
				"\n生日:" + user.getBirthday() + 
				"\n父亲:" + user.getParents().getFalther() + 
				"\n母亲:" + user.getParents().getMother());
		result = true;
		return SUCCESS;
	}
}

struts.xml配置

<package name="default" extends="json-default" namespace="/">
	<!-- 使用json格式想服务器发送数据 -->
		<interceptors>
			<interceptor-stack name="IStack">
				<interceptor-ref name="json" />
				<interceptor-ref name="defaultStack" />
			</interceptor-stack>
		</interceptors>
		<default-interceptor-ref name="IStack" />
	<!-- 使用json格式想服务器发送数据 -->
	
		<action name="addUserAction" class="net.arisu.module.user.event.AddUserAction">
			<result name="success" type="json">/test.jsp</result>
		</action>
	</package>

页面

jsonBuildWithObject("parents",parentsKeys,parentsValues),表示自定义对象,parents对应user内的自定义对象,parentsKeys和parentsValues为parents中的属性和值;

jsonBuild("user",key,value,1)中,user对应action中的user,key和value为user中的属性和值,1表示user中包含n个自定义对象(这里就parents一个),value数值的值会比key多出n个;

<title>test</title>
	<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
	<script type="text/javascript" src="js/stringUtils.js"></script>
  	<script type="text/javascript">
  		$(function(){
  		});
  		
  		function add() {
			var parentsKeys = new Array("falther", "mother");
			var parentsValues = new Array($("#falther").val(), $("#mother").val());
			var key = new Array("username", "birthday");
			var value = new Array($("#username").val(), $("#birthday").val(),
					jsonBuildWithObject("parents", parentsKeys, parentsValues));
//组合json数据格式,方便发送
			var json = jsonBuild("user", key, value, 1);
		
			$.ajax({
				type : "post",
				data : json,
				url : "addUserAction.action",
				contentType : "application/json",
				success : function(returnedData, status) {
					if (!returnedData.result) {
						alert("error");
					} else {
						alert("success");
					}
				}
			});
  		}
  	</script>	
</head>

<body>
	用户名 <input id="username" type="text" value="张三"/>
	生日	  <input id="birthday" type="text" value="2000-11-11" checked="checked">
	父亲      <input id="falther" type="text" checked="checked" value="李四">
	母亲	  <input id="mother" type="text" checked="checked" value="王五"><br>
	<input type="button" value="添加" onclick="add()">
</body>

js工具类,stringUtils.js,调用的方法如上,

/**
 * 描述:拼接json字符串
 * @param objectName 对象名称
 * @param key 属性名称
 * @param value 属性值
 * @returns {String}
 * @version: 1.0  
 * @date: 2012-10-13 上午10:46:10 
 */
function jsonBuild(objectName, key, value) {
	var result = "{'" + objectName + "':{'";
	for ( var i in value) {
		if (i < key.length) {
			if(i < key.length - 1) {
				result += key[i] + "':'" + value[i] + "','";
			} else {
				if (key.length != value.length) 
					result += key[i] + "':'" + value[i] + "',";
				else
					result += key[i] + "':'" + value[i] + "'}";
			}
		} else {
			if (i == value.length - 1) 
				result += value[i] + "}";
			else 
				result += value[i] + ",";
		}
	}
	result += "}";
	return result;
}

/**
 * 描述:拼接json字符串
 * @param objectName 对象名称
 * @param key 属性名称
 * @param value 属性值
 * @returns {String}
 * @version: 1.0  
 * @date: 2012-10-13 上午10:46:10 
 */
function jsonBuildWithObject(objectName, key, value) {
	var result = "'" + objectName + "':{'";
	for ( var i in key) {
		if (i < key.length - 1)
			result += key[i] + "':'" + value[i] + "','";
		else
			result += key[i] + "':'" + value[i] + "'}";
	}
	return result;
}

相关推荐