尝试将JavaScript对象传递给Spring MVC。我收到400错误的请求错误。尝试了所有不同的方法,但仍然没有运气。我已经附加了Controller,我在JS和Java中传递的对象以及响应。将不胜感激。当我将@RequestBody更改为@ModelAttribute时,我在控制器中接收到参数,但整数为零,数组为空。
控制器
@RequestMapping(value="/getInstrumentsByTypeMakeModel" , method=RequestMethod.GET)
public @ResponseBody List<Instrument> getInstrumentsByTypeMakeModel(@RequestBody SearchInstrument search) {
// do Something and create searchResult;
return searchResult;
}
JavaScript
var searchInstrument = {
operator: siteOperator,
companyId:loggedInUserCompanyId ,
isServiceProvider:isServiceProvider ,
types:selectedType,
makes:selectedMake,
models:selectedModel,
typeOthers:selectedTypeOther,
makeOthers:selectedMakeOther,
modelOthers:selectedModelOther
};
jQuery.ajax({
url:server_name+ "/getInstrumentsByTypeMakeModel",
type: "GET",
dataType: "JSON",
data:JSON.stringify(searchInstrument),
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
console.log(resultData);
},
error: function(jqXHR, status) {
// error handler
}
});
SearchInstrument类
public class SearchInstrument {
public SearchInstrument(){
}
public SearchInstrument(int operator,int companyId, boolean isServiceProvider,
List<Integer> types,List<Integer> makes, List<Integer> models,
List<String> typeOthers,List<String> makeOthers,List<String> modelOthers
){
this.operator=operator;
this.companyId=companyId;
this.types=types;
this.makes=makes;
this.models=models;
this.typeOthers=typeOthers;
this.makeOthers=makeOthers;
this.modelOthers=modelOthers;
}
private int operator;
private int companyId;
private boolean isServiceProvider;
private List<Integer> types=new ArrayList<Integer> ();
private List<Integer> makes=new ArrayList<Integer> ();
private List<Integer> models=new ArrayList<Integer> ();
private List<String> typeOthers=new ArrayList<String> ();
private List<String> makeOthers=new ArrayList<String> ();
private List<String> modelOthers=new ArrayList<String> ();
//getters and setters
}
[这是参数] [https://i.stack.imgur.com/2cxde.png]
[这是URL:] [https://i.stack.imgur.com/BPMaS.png]
答案 0 :(得分:0)
我不确定,但是结合GET请求并尝试传递一个对象并不是最好的主意,这就是为什么您在URL中看到searchController
JS对象的原因第二张图片。
以下question有更详尽的解释。
我认为您应该尝试将其转换为POST请求。
或者,如果您出于某种原因仍希望将其保留为GET,则应在URL中将对象作为参数传递,并在控制器中使用@RequestParam。