相关疑难解决方法(0)

将javascript对象数组作为参数发送到控制器

问题非常自我解释.我想通过POST表单发送2个不同的对象数组,而没有ajax到我的控制器.

由于params的大小,我将我的问题改为使用ajax并使用get请求.目前获得400(不良请求).我不知道为什么.请看一下...

我有对象:

var phone = {phoneId:"", phoneNumber:"", phoneType:""};
var schedule = {scheduleId:"", time:"", day:""};
Run Code Online (Sandbox Code Playgroud)

我放入一个javascript数组:

var phones = [phone1, phone2, phone3];
var schedules = [schedule1, schedule2];
Run Code Online (Sandbox Code Playgroud)

我使用ajax发送:

var data = {
    index: id,
    schedules: schedules,
    phones: phones
}
var url = "/myController/myUrl"

$.getJSON(url, data, function(result){
    if(result.ok){
         $('#messageAlertSuccess').show();
    } else {
         $('#messageAlertError').show();    
    }
});
Run Code Online (Sandbox Code Playgroud)

我创建了包装类来映射它们,如下所示:

public class PhoneWrapper(){
    private String phoneId;
    private String phoneNumber;
    private String phoneType;
}
Run Code Online (Sandbox Code Playgroud)

当然,scheduleWrapper遵循相同的约定.

这是我的控制器中的方法:

@ResponseBody
@RequestMapping(value="/myUrl", method=RequestMethod.GET)
public Result doSomething(@RequestParam("index") int index,
                          @RequestParam("phones") Set<PhoneWrapper> …
Run Code Online (Sandbox Code Playgroud)

javascript java spring spring-mvc

5
推荐指数
1
解决办法
8335
查看次数

如何使用Spring RestTemplate发送数组?

如何使用Spring RestTemplate发送数组参数?

这是服务器端实现:

@RequestMapping(value = "/train", method = RequestMethod.GET)
@ResponseBody
public TrainResponse train(Locale locale, Model model, HttpServletRequest request, 
    @RequestParam String category,
    @RequestParam(required = false, value = "positiveDocId[]") String[] positiveDocId,
    @RequestParam(required = false, value = "negativeDocId[]") String[] negativeDocId) 
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

这就是我尝试过的:

Map<String, Object> map = new HashMap<String, Object>();
map.put("category", parameters.getName());
map.put("positiveDocId[]", positiveDocs); // positiveDocs is String array
map.put("negativeDocId[]", negativeDocs); // negativeDocs is String array
TrainResponse response = restTemplate.getForObject("http://localhost:8080/admin/train?category={category}&positiveDocId[]={positiveDocId[]}&negativeDocId[]={negativeDocId[]}", TrainResponse.class, map);
Run Code Online (Sandbox Code Playgroud)

以下是实际的请求URL,这显然是不正确的:

http://localhost:8080/admin/train?category=spam&positiveDocId%5B%5D=%5BLjava.lang.String;@4df2868&negativeDocId%5B%5D=%5BLjava.lang.String;@56d5c657`
Run Code Online (Sandbox Code Playgroud)

一直试图搜索但无法找到解决方案.任何指针将不胜感激.

java rest spring

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

java ×2

spring ×2

javascript ×1

rest ×1

spring-mvc ×1