如何将ajax请求数据作为类发送到Spring mvc控制器?

时间:2016-07-09 10:29:18

标签: jquery ajax spring-mvc

我正在向Spring MVC控制器发送一个AJAX请求,如下所示:

var filters = {
    visual: visual, 
    Name: params['Name'], 
    Address: params['Address'], 
    documentType: params['documentType'], 
    itemQualifier: getItemQualifier(),
    itemIdentifier: params['itemIdentifier'], 
    currency: getCurrency(), 
    sellSide: getSellSide()
};

$.ajax({                                                                    
    type: "POST",
    url: "/reports/savefilters",
    data: filters,
    success: function(response) {
        alert('filters saved successfully: ' + response);
    },
    error: function(e) {
        alert('Error while saving filters: ' + e.message);
    }
});
@RequestMapping(value = "/savefilters", method = RequestMethod.POST)
public @ResponseBody String saveFilters(@RequestParam("visual") String visual, @RequestParam(value = "Name[]", required = false) String[] Name, 
        @RequestParam(value = "Address[]", required = false) String[] Address, @RequestParam(value = "documentType[]", required = false) String[] documentType, 
        @RequestParam("itemQualifier") String itemQualifier, @RequestParam(value = "itemIdentifier[]", required = false) String[] itemIdentifier, @RequestParam("currency") String currency,
        @RequestParam("sellSide") String sellSide, HttpServletRequest request)
{
    try
    {
        System.out.println("saveFilters");
        new DisplayService().saveFilters("ID", visual, Name, Address, documentType, itemQualifier, itemIdentifier, currency, sellSide);
        return "success";
    }
    catch (Exception ex)
    {
        return "error occured while inserting/updating db";
    }
}

我希望将所有这些参数作为类传递,而不是像这样发送。

如何从AJAX调用中作为类传递,如何在Spring MVC控制器代码中接收它?有什么建议吗?感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用请求对象并使用它来获取所有参数,如下所示。

public @ResponseBody String saveFilters(HttpServletRequest request){

String visual = request.getParameter("visual")

}

答案 1 :(得分:0)

只需创建一个与您的Javascript变量filters匹配的Java类。

public class Filters {
    private String name;
    private List<String> address;
    private List<String> documentType;
    private String itemQualifer;
    private String itemIdentifier;
    private String Currency;
    private String sellSide;

    // getters and setters must exists but I omitted for brevity.
}

MVC控制器:

@RequestMapping(value = "/savefilters", method = RequestMethod.POST)
public @ResponseBody String saveFilters(Filters filters) {

}