Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将JSON对象作为PathVariable传递给spring控制器_Java_Json_Spring_Angular - Fatal编程技术网

Java 如何将JSON对象作为PathVariable传递给spring控制器

Java 如何将JSON对象作为PathVariable传递给spring控制器,java,json,spring,angular,Java,Json,Spring,Angular,我正在使用angularjs开发spring应用程序。我想将JSON对象作为@PathVariable传递给spring控制器,但在下面的代码中,当将JSON对象作为PathVariable传递时,它没有击中spring控制器,也没有显示任何错误。有输入吗 示例代码: js: MyService.js myService.sendJSON = function (myJSONData,fd) { var deferred = $q.defer(); var my

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

示例代码: 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");
   }
@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..
spring-servlet.xml 我在sprig-servlet.xml配置文件中添加了以下

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10000000"/>
</bean>
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 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");
   }
@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..
@控制器
@请求映射(“/dataStack”)
公共类GetDataController{
@RequestMapping(value=“/getAllDataInfo”,method=RequestMethod.POST)
公共@ResponseBody
字符串uploadMultipleFileHandler(MultipartTTpServletRequest请求){
System.out.println(“在spring中上载多个文件”);
List multiPartFileList=req.getFiles(“文件”);
System.out.println(“in multiPartFileList”+multiPartFileList.size());//大小始终为零
String[]json=(String[])req.getParameterMap().get(“json”);//获取提交的值
//代码在这里。。
我正在获取json对象的值,但无法获取文件详细信息。 multiPartFileList.size()的大小为零。我尝试只添加类MultiFileResolverConfig并删除spring-servlet.xml中的
声明,但文件详细信息仍然没有传递给spring控制器

  • 在您的客户端代码中,即MyService.js发送正确的内容类型,在您的示例中是application/json

    headers : {
        'Content-Type': application/json
    }
    
  • 在服务器端,即spring控制器:,通过以下方式让请求映射器知道传入请求的数据类型:

    @RequestMapping(value=“/{myJSONData}/getAllDataInfo”,method=RequestMethod.POST,consumes=MediaType.APPLICATION\u JSON)


  • 您可以以对象(DTO)的形式发送

    如下

    var createEvaluationRequestObject = {"test":"Value1","test2":"value2"};
    var createEvaluationRequest       = JSON.stringify (createEvaluationRequestObject);
    
    试试这个,应该有用

    更新日期:2018年6月22日

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

    @Configuration
    public class SomeConfig {
       @Bean
       public MultipartResolver multipartResolver() {
          return new CommonsMultipartResolver();
       }
    }
    
    注意:豆子的名字很重要

    另一方面,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);
            ...
    
    在控制器中,修复请求映射,并使其接受
    multipartttpServletRequest
    参数,而不是
    List

    我想这应该对你有好处


    HTH

    为什么要传递带变量的json对象,应该选择@RequestParam,或者最好的方法是使用POST和pass-through-RequestBody。我尝试使用POST和pass-through-RequestBody,如果您在上面的代码中看到我的POST方法,那么我会传递url、fd、配置信息,以及当我将此json对象作为其他参数添加并修改时d spring controller接受RequestBody它仍然无法识别spring控制器…您也必须更改请求映射url。我需要将文件信息以及JSON对象传递给spring控制器。要传递文件信息,我需要设置标题:{“内容类型”:未定义}在MyService.js中,正如您所说的发送json对象,头应该是application/json,但它不允许文件发送..关于如何将文件信息以及json对象发送到spring控制器的任何输入。我可以将json转换为字符串并作为PathVariable发送,但问题是当对象太长或包含特殊字符不允许作为PathVariable发送..@PaulWarren-spring控制器中的文件大小为零,spring控制器中的multiPartFileList为零,我是否需要在spring控制器中包含任何头信息以将文件信息从angular传递到spring控制器,请告知..thanksI可以通过转换JSON>Stri发送ngify但问题是我的JSON对象可能太长,包含特殊字符。因此它不允许我作为PathVariable发送。当JSON没有特殊字符时,我可以将其作为字符串成功发送到spring controller。但在我的情况下,它可能包含许多特殊字符,JSON中的值可能很长。可以吗我将文件信息和JSON对象作为RequestParam和RequestBody发送..我按照您的建议尝试,但它不支持getParameterMap-它说无法解析方法getParameterMap..我已将MyService修改为:$http.post(repUrl,formData,{transformRequest:function(data,headersGetterFunction){return data;}然后(函数(响应){console.log(“响应”+response);},以及它如何命中spring控制器,但spring控制器中的multiPartFileList大小为零。即,List multiPartFileList=req.getFiles(“文件”);//大小为零,文件信息不存在。任何输入都会有帮助。@Paul Warren-我正在用spring和angularjs尝试上述代码,正如用户nan提到的,spring控制器中的多部分文件列表大小为零。在传递请求和spring控制器中,我们是否需要包含任何特殊的头?@user3684675请参阅我的最新答案。让我知道这是否对你有效。@PaulWarren-谢谢你的更新。.我已经按照你上面的建议尝试过了,但没有成功
    @Configuration
    public class SomeConfig {
       @Bean
       public MultipartResolver multipartResolver() {
          return new CommonsMultipartResolver();
       }
    }
    
    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);
            ...
    
    @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.sendJSON = function (fd) {
             var deferred = $q.defer();
             var myUrl = applnURL + '/dataStack/getAllDataInfo.form';
            ...