温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Angular.js前台传list数组由后台spring MVC接收数组的示例分析

发布时间:2021-07-22 14:50:16 来源:亿速云 阅读:240 作者:小新 栏目:web开发

这篇文章主要介绍了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);

  }

 }

感谢你能够认真阅读完这篇文章,希望小编分享的“Angular.js前台传list数组由后台spring MVC接收数组的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI