简体   繁体   中英

How to pass JSON array from AngularJS Controller to the Spring Controller?

I am making SPA using AngularJS in Spring 4 with Hibernate 5.

I'm getting an error while passing JSON array from the AngularJS controller to the Spring Controller.

All fields value successfully coming in angular JSON array, but not passing in Spring controller.

Error: Could not read JSON: ; nested exception is com.google.gson.JsonSyntaxException:

My project structure is like below.

Spring_Hibernate_MVC =src -com->karmesh->mvcApp->controller->register->RegisterController.java =WebContent -js->app->RegisterController.js -Views->Register.html

Register,html

<div id="DivRegisterMain" ng-controller="RegisterController">   
    <form name="myForm" novalidate>

:::://Form fields here.
        <input type="submit" value="SubmitTest" ng-click="submit()" ><br>
    </form>

</div>

app.js

var routeApp=angular.module("RouteApp",['ngRoute']);

RegisterController.js

routeApp.controller("RegisterController", function($scope, $http) {

    $scope.regJson = {
        "is" : 1,   
        "fname" : "",
        "lname" : "",
        "gender" : "",
        "dob" : "",
        "email" : "",
        "contact" : "",
        "yop" : "",
        "degree" : "",
        "branch" : "",
        "perc" : "",
        "state" : "",
        "city" : ""

    };

$scope.studentList = [];

$scope.submit = function() {

        var req = {
                 method: 'POST',                 
                 url: 'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',              
                 data: $scope.studentList,

        };

        $http(req).
        then(function(response){
            console.log(response); // prints true or false
            if (response)
              console.log("in success");
            else 
               console.log("in fail");
            $scope.studentList=[];
        }, function(response){
            console.log(response.status);
            console.log("in error");

        });


    };

RegisterController.java

@EnableWebMvc
@RestController
@RequestMapping("/")
public class RegisterController {

    @Autowired
    private RegisterService registerService;

    public RegisterController() {
        System.out.println(this.getClass().getSimpleName() + "created..");
    }


    @ResponseBody
    @RequestMapping(value="/registerStudent.do", method = RequestMethod.POST)   
    public boolean registerStudent(@RequestBody List<RegisterDTO> stdList) {    
        System.out.println("inside controller..");

        if (stdList != null) {  
        System.out.println("success...");
          }
          return registerService.isStudentExist(stdList);

    }
}

use JSON Serialization/Deserialization

your request should be

            var req = {
                 method: 'POST',    url:'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',              
                 data: JSON.stringify($scope.studentList),
           };

your spring controller

    @ResponseBody
    @RequestMapping(value="/registerStudent.do", method = RequestMethod.POST)   
    public boolean registerStudent(@RequestBody string data) { 
        List<RegisterDTO> stdList = JsonConvert.DeserializeObject<RegisterDTO>(data); // find java jsondeserializer
        System.out.println("inside controller..");

        if (stdList != null) {  
            System.out.println("success...");
         }
          return registerService.isStudentExist(stdList);

    }  

您在请求中缺少contentType: 'application/json'

RegisterController.js

$scope.submit = function() {

        var req = {
                 method: 'POST',                 
                 url: 'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',              
                 data: angular.toJson($scope.studentList),// note this

        };

    };

download gson jar file.

RegisterController.js

@ResponseBody
    @RequestMapping(value = "/registerStudent.do", method = RequestMethod.POST)
    public boolean registerStudent(@RequestBody String data) {

        Gson googleJson = new Gson();
        ArrayList stdList = googleJson.fromJson(data, ArrayList.class);

        if (stdList != null) {
            // store your stdList
        }
        return registerService.isStudentExist(stdList);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM