首页 > 语言 > JavaScript > 正文

Angular.js前台传list数组由后台spring MVC接收数组示例代码

2024-05-06 15:13:35
字体:
来源:转载
供稿:网友

前言

本文主要给大家介绍了关于Angular.js前台传list数组由后台spring MVC接收数组的相关内容,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍吧。

在开发中有时候需要在前台自定义对象,然后把对象封装在list中,在传送到后台,这样的思想也比较合理,直接来看示例代码:

1. 前台代码

$scope.saveScore = function () { $scope.userScoreList = new Array();//自定义数组 angular.forEach ($scope.records, function (record, index) {     if (record.score != null) {   $scope.userScoreModel = {'userAnswerId': null,'score': null};//自定义对象结构   $scope.userScoreModel.userAnswerId = record.userAnswerId;//赋值   $scope.userScoreModel.score = record.score;       $scope.userScoreList.push($scope.userScoreModel);//把对象封装在集合中   debugger;  } });   if ($scope.userScoreList != null && $scope.userScoreList.length > 0) {  var fd = new FormData();// 使用angularJS的FormData封装要传送的数据  var userScoreRecords = angular.toJson($scope.userScoreList);//把对象(集合)转换为json串  fd.append('userScoreRecords', userScoreRecords);//参数放入formData中  debugger;//使用 debugger模式查看传值情况  $http.post('/reviewProcess/save', fd, { //使用post方法 传送formdata对象   transformRequest: angular.identity, //使用angular传参认证   headers: {    'Content-Type': undefined //设置请求头   }  })  .success(function (data){   toastr.success("success");  })  .error(function (data) {   toastr.success("failed");  }); }}; 

2. 后台接收

@ResponseBody @RequestMapping(value = "/reviewProcess/save", method = RequestMethod.POST) public void saveUserScore (@RequestParam("userScoreRecords") String userScoreRecords) { //使用requestparam接收前台传送的json串  System.out.println(userScoreRecords);  ObjectMapper mapper = new ObjectMapper(); // 使用fastJson的ObjectMapper反序列化json串为对象  UserScoreModel record = null;  try {   JSONArray jsonArray = new JSONArray (userScoreRecords); //在后台把json串转换为json数组   for (int i =0; i < jsonArray.length(); i++) {    record = mapper.readValue(jsonArray.getJSONObject(i).toString(), UserScoreModel.class); //获取json数组的json对象并且反序列化为对应的对象    System.out.println(record); // 得到对象后后台即可操作   }  } catch (Exception e) {   logger.error(e.getMessage(), e);  } } 

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对错新站长站的支持

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选