如何将JSON对象作为PathVariable传递给spring控制器 [英] how to pass JSON object as a PathVariable to spring controller

查看:111
本文介绍了如何将JSON对象作为PathVariable传递给spring控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angularjs开发Spring应用程序.我想将JSON对象作为 @PathVariable 传递给spring控制器,但是使用下面的代码,当将JSON对象作为PathVariable传递时,它没有命中spring控制器,并且没有显示还有任何错误.有输入吗?

I am working on spring application with angularjs. I want to pass the JSON object as a @PathVariable to the spring controller, but with my below code, when passing the JSON object as a PathVariable it is not hitting the spring controller, and it is not showing any error too.Any inputs?

示例代码:js:

myApp.controller('passJSONTestController', function ($rootScope, $scope, MyService) {
     $scope.submitdata=function(){
        $scope.myJSONData = [
            {   'name':$scope.name,
                'sinNumber': $scope.sinNo,
                'status': $scope.status,
                'message':$scope.message,
            }
        ];
        var fd=new FormData();
        angular.forEach($scope.files,function(file){
            console.log("file " + file);
            fd.append('file',file);
        });
        MyService.sendJSON($scope.myJSONData,fd).then(
            function (response) {
                //
            },
            function (errResponse) {
             }
        );
    }
});

MyService.js

MyService.js

myService.sendJSON = function (myJSONData,fd) {
         var deferred = $q.defer();
        var myUrl = applnURL + '/dataStack/' + myJSONData + '/getAllDataInfo.form';
          var config = {
            transformRequest: angular.identity,
             headers : {
                'Content-Type': undefined
            }
        }
         $http.post(repUrl, fd, config ).then(function (response) {
        }, function (response) {
         });
         return deferred.promise;
     }

弹簧控制器:

@Controller
@RequestMapping("/dataStack")
public class GetData {
 @RequestMapping(value = "/{myJSONData}/getAllDataInfo", method = RequestMethod.POST)
    public
    @ResponseBody
    String sendInfo(@RequestParam("file") List<MultipartFile> multiPartFileList,@PathVariable("myJSONData") List<MyDTO> myDTO){                          
        System.out.println("In Spring controller");
   }

为什么传递的请求未命中spring控制器?PS:如果我在spring控制器中删除了pathvariable并将其从mySerivce.js中删除,则说明它正在触击spring控制器.

Why is the request passed not hitting the spring controller? PS: If i remove the pathvariable in spring controller and remove it from mySerivce.js, then it is hitting the spring controller.

-------------编辑(更新的代码)--------------我添加了下面的类:

-------------EDITED (Updated code)-------------- I have added the below class:

@Configuration
public class MultiFileResolverConfig {
    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() {
        System.out.println("--In configuration file multipartResolver--");
        return new CommonsMultipartResolver();
    }
}

spring-servlet.xml我在sprig-servlet.xml配置文件中的< bean> 下面添加了

spring-servlet.xml I have added below <bean> in sprig-servlet.xml configuration file

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10000000"/>
</bean>

html代码:

<html>
..elements for name,sinNumber,status,message
  <input type = "file"  name="file" file-model="file" multiple/>
..//submit button
</html>

js代码:

 myApp.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

    myApp.controller('passJSONTestController', function ($rootScope, $scope, MyService) {
         $scope.submitdata=function(){
            $scope.myJSONData = [
                {   'name':$scope.name,
                    'sinNumber': $scope.sinNo,
                    'status': $scope.status,
                    'message':$scope.message,
                }
            ];
            var fd=new FormData();
            angular.forEach($scope.files,function(file){
                console.log("file " + file);
                fd.append('file',file);
            });
            fd.append("json",$scope.myJSONData);
            MyService.sendJSON(fd).then(
                function (response) {
                    //
                },
                function (errResponse) {
                 }
            );
        }
    });

service.js

service.js

myService.sendJSON = function (fd) {
         var deferred = $q.defer();
        var myUrl = applnURL + '/dataStack/getAllDataInfo.form';
          var config = {
            transformRequest: angular.identity,
             headers : {
                'Content-Type': undefined
            }
        }
         $http.post(myUrl, fd, config ).then(function (response) {
        }, function (response) {
         });
         return deferred.promise;
     }

弹簧控制器:

@Controller
@RequestMapping("/dataStack")
public class GetDataController{
    @RequestMapping(value = "/getAllDataInfo", method = RequestMethod.POST)
    public @ResponseBody
    String uploadMultipleFileHandler(MultipartHttpServletRequest req) {

        System.out.println("in spring upload multiple files");
        List<MultipartFile> multiPartFileList = req.getFiles("file");
        System.out.println("in multiPartFileList " + multiPartFileList.size());//size is always zero
        String[] json = (String[]) req.getParameterMap().get("json");//getting the values submitted
        //code here..

我正在获取json对象的值,但无法获取文件的详细信息.multiPartFileList.size()的大小为零.我尝试仅添加类MultiFileResolverConfig并删除spring-servlet.xml中的< bean> 声明,但仍未将文件详细信息传递给spring控制器.

I am getting the values for json object but unable to get the files details. The size of multiPartFileList.size() is zero.I tried adding only class MultiFileResolverConfig and removing the <bean> declaration in spring-servlet.xml but still the file details is not been passed to the spring controller.

推荐答案

更新06/22/2018

Update 06/22/2018

在涉及多部分请求时,请注意,Spring Boot和Spring MVC的工作方式有所不同.默认情况下,Spring MVC不会提供 ,因此无法解析多部分请求.您必须在ApplicationContext中提供一个"multipartResolver" bean.但是,Spring MVC确实为此提供了两种实现. StandardServletMultipartResolver CommonsMultipartResolver .在您的应用程序上下文中配置其中任何一个都可以.例如:

When it comes to multipart requests note that Spring Boot and Spring MVC work differently. By default Spring MVC does not provide a MultipartResolver and therefore cannot resolve multipart requests. You have to provide a "multipartResolver" bean in your ApplicationContext. However, Spring MVC does provide two implementations for this; StandardServletMultipartResolver and CommonsMultipartResolver. Configuring either of these into your application context will work. For example:

@Configuration
public class SomeConfig {
   @Bean
   public MultipartResolver multipartResolver() {
      return new CommonsMultipartResolver();
   }
}

注意:bean的名称很重要.

NB: the name of the bean is important.

另一方面,Spring Boot将代表您自动配置 StandardServletMultipartResolver 的实例,因此能够立即"解决多部分请求.

On the other hand Spring Boot will autoconfigure an instance of StandardServletMultipartResolver on your behalf and is therefore able to resolve multipart requests "out of the box".

原始答案

您也应该使用FormData对象传递其他数据.

You should pass the additional data using the FormData object too.

更改您的客户端代码以附加其他数据:

Change your client-side code to append the additional data:

myApp.controller('passJSONTestController', function ($rootScope, $scope, MyService) {
     $scope.submitdata=function(){
        $scope.myJSONData = [
            {   'name':$scope.name,
                'sinNumber': $scope.sinNo,
                'status': $scope.status,
                'message':$scope.message,
            }
        ];
        var fd=new FormData();
        angular.forEach($scope.files,function(file){
            console.log("file " + file);
            fd.append('file',file);
        });

        // do this instead
        data.append('json', JSON.stringify($scope.myJSONData);
        ...

在您的控制器中修复请求映射,并使其接受 MultipartHttpServletRequest 参数而不是 List< MultipartFile> :

In your controller fix the request mapping and make it accept MultipartHttpServletRequest parameter instead of List<MultipartFile>:

@Controller
@RequestMapping("/dataStack")
public class GetData {
 @RequestMapping(value = "/getAllDataInfo", method = RequestMethod.POST)
    public
    @ResponseBody
    String sendInfo(MultipartHttpServletRequest req){        

       List<MultipartFile> multiPartFileList = req.getFiles("file");
       ...

       String[] json = req.getParameterMap().get("json");

       // Jackson deserialization...but you could use any...Gson, etc
       ObjectMapper mapper = new ObjectMapper();
       TypeReference<Map<String,String>> typeRef = new TypeReference<Map<String,String>>() {};
       Map<String,String> data = mapper.readValue(json[0], typeRef);
       ...

确保更新MyService以便发布到新的请求映射:

Make sure you update MyService to post to the new request mapping:

myService.sendJSON = function (fd) {
         var deferred = $q.defer();
         var myUrl = applnURL + '/dataStack/getAllDataInfo.form';
        ...

我认为应该为您做.

HTH

这篇关于如何将JSON对象作为PathVariable传递给spring控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆