Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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?

share|improve this question

4 Answers 4

up vote 2 down vote accepted

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;

});
share|improve this answer
1  
Thanks a ton. Works like a charm. –  chaity Apr 22 at 11:21

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
})},
share|improve this answer
    
How to collect that in angular? As in, I need to display fields from that on to my jsp page. How to do that? –  chaity Apr 22 at 9:29
    
e.g. $scope.folder = data.folderPath –  Stijn Geukens Apr 22 at 9:52

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

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.