struts2 前端向后端传送复杂对象/JSON

javascript方法: JSON.stringify(jsonObj), 将JSON对象转为字符串

 

 

项目中需要将复杂的对象从前端传到后端, 通过struts2的拦截器, 直接转换注入到action的属性中

比如 private List<Bean> test;

 

当然可以将data写成:

 

{	"test[0].note":"note a", "test[0].username":"username a",
	"test[1].note":"note b", "test[1].username":"username b"
}
 

 

直接将obj做为data传给$.ajax不行, struts2没配置json拦截器也不行

 

javascript:

var jsonObj = {
	"test":
		[{"note":"note a", "username":"username a"}, 
		 {"note":"note b", "username":"username b"}
		]
};
var str = JSON.stringify(jsonObj);
//console.log("result: "+str);
$.ajax({
	url: "input.action",
	contentType: 'application/json',
	data: str,
	type: "post",
	datatype: "json",
	success: function(data){
		console.log(data);
	}
});
  

bean:

public class Bean{
	private String note;
	private String username;
	//getter and setter
}

 

action:

public class TestAction extends BaseAction{
	private List<Bean> test;
	public List<Bean> getTest() {
		return test;
	}
	public void setTest(List<Bean> test) {
		this.test = test;
	}

	public String input(){
		System.out.println(test);
		for(Bean bean: test){
			System.out.println(bean.getNote());
		}
		return SUCCESS;
	}
}

 

 

struts2:

<package name="test" namespace="/test" extends="json-default">
	<interceptors>
		<interceptor-stack name="def">
			<interceptor-ref name="defaultStack"></interceptor-ref>
			<interceptor-ref name="json"></interceptor-ref>
		</interceptor-stack>
	</interceptors>
	<default-interceptor-ref name="def"></default-interceptor-ref>
		
	<action name="input" class="testAction" method="input">
		<result type="json"></result>
	</action>
</package>
spring配置省略
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值