2

FrontEnd: jsp with AngularJS BackEnd: Spring MVC/Java

I am uploading a file using ng-flow, angularJS. Source: https://github.com/flowjs/ng-flow

File upload is successful. I need to return a json from my Spring Controller. Any clues how to go about it? P.S. can't find where to put in .success() function, if at all that is applicable.

Spring Controller:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
        public String uploadFileHandler(@RequestParam("file") MultipartFile file, Model model) {
       //Upload file and process

       JsonObject jo = Json.createObjectBuilder().add(path, folderPath.toString())
                                .add(aContentsAttrib, aContents)
                                .add(bContentsAttrib, bContents).build();
}

app.js code:

(function() {
    var app = angular.module('app', ['flow'])
    .config(['flowFactoryProvider', function (flowFactoryProvider) {
      flowFactoryProvider.defaults = {
        target: 'upload',
        permanentErrors: [404, 500, 501],
        maxChunkRetries: 4,
        chunkRetryInterval: 500,
        simultaneousUploads: 4
      };
      flowFactoryProvider.on('catchAll', function (event) {
        console.log('catchAll', arguments);
      });
      // Can be used with different implementations of Flow.js
      // flowFactoryProvider.factory = fustyFlowFactory;
    }]);

  app.controller('PageController', function() {
    //this.products = gems;
  });

  app.controller("TabController", function() {
    this.tab = 1;
    this.showOutput = false;
    this.viewEvents = false;

    this.isSet = function(checkTab) {
      return this.tab === checkTab;
    };

    this.changeVal = function() {
        this.viewEvents = true;
    };

    this.setTab = function(setTab) {
      this.tab = setTab;
    };
  });

})();

What exactly should be returned from the spring controller? (String/@ResponseBody String etc) How to collect that json in angular?

Harshal Patil
  • 6,284
  • 8
  • 37
  • 55
chaity
  • 163
  • 2
  • 11

4 Answers4

3

On your controller @ResponseBody should be added and the jo returned as String:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
        public @ResponseBody String uploadFileHandler(@RequestParam("file") MultipartFile file, Model model) {
       //Upload file and process

       JsonObject jo = Json.createObjectBuilder().add(path, folderPath.toString())
                                .add(aContentsAttrib, aContents)
                                .add(bContentsAttrib, bContents).build();


       return jo.toString();
}

In AngularJS, you should do this for being able to post files and then retrieve the data back:

$http({url: '/url', 
      method: 'POST',
      data: $scope.myFile,
      headers: {'Content-Type': undefined },
      transformRequest: angular.identity
}).success(data){
   $scope.myData = data;

});
Community
  • 1
  • 1
Michael
  • 3,240
  • 5
  • 21
  • 36
0

In your Spring controller you should just return an Object containing the properties you want to transfer to your angular service. This will be automatically (or by default) be converted to JSON. @RequestBody is not needed.

This return value will be available in the success callback, something like:

$http({
    method: 'POST',
    url: '...',
    }).success(function (data) {
        //data is your JSON response
})},
Stijn Geukens
  • 14,803
  • 7
  • 60
  • 100
0

If you are using Spring 3 you can do this

 @RequestMapping(value = "/getDealers", value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFileHandler() {

    }

@ResponseBody annotation directly writes the response to the response stream. You would not need a JSP. Just send the request for the controller from the browser & the controller method will write the response to the response stream.

You can parse the response using Jquery or any json library & display in the JSP Check this out

underdog
  • 4,188
  • 7
  • 38
  • 81
0

An alternate way, which I just found out. Will be useful to extract from existing code, without any modification. It does introduce an extra global variable, outside your main angular app, and might not be highly recommended, but still, posting this.

var json = {};    
var app = angular.module('app', ['flow'])
        .config(['flowFactoryProvider', function (flowFactoryProvider) {
          flowFactoryProvider.defaults = {
            target: 'processxls',
            permanentErrors: [404, 500, 501],
            maxChunkRetries: 4,
            chunkRetryInterval: 500,
            simultaneousUploads: 4
          };
          flowFactoryProvider.on('catchAll', function (event) {
            console.log('catchAll', arguments);
            this.jsonResponse = arguments[2]; //Note this change
            //json = this.jsonResponse;
            console.log(this.jsonResponse);
            json = angular.fromJson(this.jsonResponse);
          });
          // Can be used with different implementations of Flow.js
          // flowFactoryProvider.factory = fustyFlowFactory;
        }]);

'json' variable now has the json response received. You can use it for further use now. P.S. in order to check for which value of 'i' arguments[i] gives you the json, see console.

chaity
  • 163
  • 2
  • 11