Json对象解析并传递给spring控制器

时间:2017-01-13 06:23:59

标签: javascript json ajax spring

我的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}

1 个答案:

答案 0 :(得分:0)

@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错误