【问题标题】:Json object parse and pass to spring contollerJson对象解析并传递给spring控制器
【发布时间】:2017-01-13 06:23:59
【问题描述】:

我的 jsp 中有一个文件上传组件,我只接受 json 格式的文件。我想获取json文件并将其传递给spring并在spring中对json对象进行操作。

我的 javascript 如下所示

var file = this.files[0];
 var reader = new FileReader();

  var oMyForm = new FormData();
  oMyForm.append("file", this.files[0]);

 console.log('reader='+JSON.stringify(reader)) // this does not print any it prints empty as "reader={}"
console.log('oMyForm ='+JSON.stringify(oMyForm )) // this does not print any it prints empty as "oMyForm={}"
var urlpath =  "<%=request.getContextPath()%>/fileUpload";
  $.ajax({
                    data : JSON.stringify(reader),
                    type : 'POST',
                    dataType: 'json',
                    headers: { 
                        'Accept': 'application/json',
                        'Content-Type': 'application/json' 
                    },
                    url : urlpath,
                    success : function(data){
                    }
               });

Java 类

@RequestMapping(value= "/fileUpload", method=RequestMethod.POST,consumes="application/json")
    public void fileUpload(){
         //here i want to get the json object and do parsing and manipulations on the object
         System.out.println(" uploaded!");
    }

同样,当我上传文件时它会碰到控制器类,但在浏览器控制台中它会抛出错误

“NetworkError: 404 Not Found - http://localhost:8080/proj/fileUpload”

但是当我尝试从JSON.stringify(hardcoded)打印硬编码值时

Json 文件内容:

{'Gyr-x':10.11,'Gyr-y':9.66,'Gyr-z':10.93,'Temparature':30,'Pressure':101,'Humidity':15,'deviceId':1}

【问题讨论】:

  • 你怎么知道它命中了服务器?打印硬编码值是什么意思?在服务器还是客户端?
  • 它命中服务器 sysout 正在打印。打印硬编码值,而不是上传文件,而是将 json 放入变量并在浏览器控制台中打印

标签: javascript json ajax spring


【解决方案1】:
@RequestMapping(value= "/fileUpload", method=RequestMethod.POST,consumes="application/json")
public void fileUpload(@requestBody String json){
     //here i want to get the json object and do parsing and manipulations on the object
     System.out.println(" uploaded!");
}

在javascript中尝试url:fileUpload

您的页面没有点击控制器,这就是它给出 404 错误的原因

【讨论】:

  • 控制器正常命中..我正在通过调试和系统输出进行检查
  • 你现在遇到了什么问题?
猜你喜欢
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
  • 1970-01-01
  • 2011-09-05
相关资源
最近更新 更多