簡體   English   中英

如何將JSON對象作為PathVariable傳遞給spring控制器

[英]how to pass JSON object as a PathVariable to spring controller

我正在使用angularjs進行Spring應用程序。 我想將JSON對象作為@PathVariable傳遞給spring控制器,但是使用下面的代碼,當將JSON對象作為PathVariable傳遞時,它沒有命中spring控制器,並且也沒有顯示任何錯誤。

示例代碼: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.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");
   }

為什么傳遞的請求未命中彈簧控制器? PS:如果我在spring控制器中刪除了pathvariable並將其從mySerivce.js中刪除,則說明它正在觸擊spring控制器。

-------------編輯(更新代碼)--------------我添加了以下類:

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

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

<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

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控制器。

更新06/22/2018

對於多部分請求,請注意,Spring Boot和Spring MVC的工作方式不同。 默認情況下,Spring MVC的提供MultipartResolver,因此不能解析多部分請求。 您必須在ApplicationContext中提供一個“ multipartResolver” bean。 但是,Spring MVC確實為此提供了兩種實現。 StandardServletMultipartResolverCommonsMultipartResolver 將這些配置到您的應用程序上下文中將起作用。 例如:

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

注意:bean的名稱很重要。

另一方面,Spring Boot將代表您自動配置StandardServletMultipartResolver的實例,因此能夠“立即”解決多部分請求。

原始答案

您也應該使用FormData對象傳遞其他數據。

更改您的客戶端代碼以附加其他數據:

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>

@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以發布到新的請求映射:

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

我認為應該為您做。

HTH

  1. 在您的客戶端代碼中,即MyService.js發送正確的Content-Type,在您的情況下為application / json

     headers : { 'Content-Type': application/json } 
  2. 在服務器端,即spring controller :,可以通過以下方式使您的請求映射器了解傳入請求的數據類型:

    @RequestMapping(value = "/{myJSONData}/getAllDataInfo", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON)

您可以以Object(DTO)的形式發送

像下面

var createEvaluationRequestObject = {"test":"Value1","test2":"value2"};
var createEvaluationRequest       = JSON.stringify (createEvaluationRequestObject);

試試這個,它應該工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM