angularJS前台传list数组,后台springMVC接收数组
有时候需要在前台自定义对象,然后把对象封装在list中,在传送到后台,这样的思想也比较合理
1. 前台代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
$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. 后台接收
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@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); } } |