1,406   Java SpringMVC

Spring MVC框架,前端有个list集合,需要传到后端处理
网上有许多实现方法,找了个比较简单的实现方式

1,前端组装数据

		function save() {
		
		
			var data = [];
	 		$(".inputclass").each(function(){
 				if(data[$(this).attr("data-number")] == null || data[$(this).attr("data-number")] == undefined){
 					data[$(this).attr("data-number")] = {};
 				}
 				data[$(this).attr("data-number")][this.name] = this.value;
 				
 			});	
			
			var initTips = $.dialog.tips('更新任务中...', 60000, 'loading.gif');
			$.ajax({
			      type : 'POST',
			      url : basePath+"taskManage/saveDepend.do",
			      data:JSON.stringify(data), //转换成json字符串	      
			      datatype : 'json',
			      contentType : 'application/json;charset=utf-8', // 必须设置
			      async : false,
				  success : function(data) {
						initTips.close();
						if(data.result) {
							alert('保存成功!');
							window.close();
						}else {
							showDialog('更新失败!', 'error');
						}
					}
			});
		}

2,后端获取json字符串并转成对象

 @SuppressWarnings({ "unchecked", "rawtypes" })
 @RequestMapping("/saveDepend")
 // 需要给参数添加 @RequestBody
 public @ResponseBody Map<String, Object> saveDepend(@RequestBody List tbUcTaskDependList) {
 Map<String, Object> map = new HashMap();

 
 for(int i=0;i<tbUcTaskDependList.size();i++) {
 TbUcTaskDepend tbUcTaskDepend = tbUcTaskDependList.get(i);
 
 try {
 tbUcTaskDependBo.save(tbUcTaskDepend);
 } catch (Exception e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }

 return map;
 }

注意问题:
1,以上实现需要SpringMVC的配置满足两个条件,
(1)The request’sContent-Type header must be set toapplication/json.
(2)The JacksonJSON library must be available on the application’s classpath.

第一个在前端json提交时设置,

contentType : 'application/json;charset=utf-8', // 必须设置

第二个需要Spring项目的xml文件设置

  <dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-core-asl</artifactId>
 </dependency>
 <dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-mapper-asl</artifactId>
 </dependency>

详情请查看:http://blog.csdn.net/tiantiandjava/article/details/46125141

2,更多接收list的方法,请查看
http://blog.csdn.net/tiantiandjava/article/details/46125141
http://blog.csdn.net/lutinghuan/article/details/46820023




Leave a Reply

Your email address will not be published. Required fields are marked *