使用Jquery Ajax将列表传递给Spring Controller

时间:2017-07-20 20:32:16

标签: jquery ajax spring spring-mvc spring-boot

我们的代码中有多个ModelBean类。我们需要使用modelBean调用向主要list类(如objectstringAJAX等)发送不同的数据分类。我尝试了以下代码并能够发送String类型,但不能发送listobject。从AJAX开始,我们需要发送到Spring controller。主Bean类是MainBean

public class MainBean {

private String name;
private List<Truck> truckList;
private Address address;

}
public class Address {
    private String houseNumber;
    private String area;
    private String city;
}

public class Truck {
    private String truckName;
    private Type type;
}

public class Type{
    private String medium;
    private String heavy;
}

控制器类

@RequestMapping(value="/saveData", method = RequestMethod.POST)
    public ModelAndView saveData(@ModelAttribute("mainBean")MainBean mainBean){

        truckService.saveData(mainBean);

        return new ModelAndView("redirect:/main");
    }

AJAX代码

$( document ).ready(function() {

var url = window.location;

// SUBMIT FORM
$("#customerForm").submit(function(event) {
    // Prevent the form from submitting via the browser.
    event.preventDefault();
    ajaxPost();
});


function ajaxPost(){

    // PREPARE FORM DATA
    var formData = {
        firstname : $("#name").val(),
        truckName :  $("#truckName").val(),
        medium :  $("#medium").val(),
        heavy :  $("#heavy").val(),
        houseNumber :  $("#houseNumber").val()
    }

    // DO POST
    $.ajax({
        type : "POST",
        contentType : "application/json",
        url : url + "/postcustomer",
        data : JSON.stringify(formData),
        dataType : 'json',
        success : function(result) {
            if(result.status == "Done"){
                $("#postResultDiv").html("<strong>" + "Success" + "</strong>");
            }else{
                $("#postResultDiv").html("<strong>Error</strong>");
            }
            console.log(result);
        },
        error : function(e) {
            alert("Error!")
            console.log("ERROR: ", e);
        }
    });
}

})

1 个答案:

答案 0 :(得分:0)

您需要将数据作为String发送到控制器,一旦将数据导入控制器,您可以将其解析为List,或者您想要的任何类型:

@RequestMapping(value="/saveData", method = RequestMethod.POST)
public ModelAndView saveData(@ModelAttribute("mainBean")String mainBeanString){


    ObjectMapper mapper = new ObjectMapper();
    List<MainBean> itemsFromController = mapper.readValue(mainBeanString, mapper.getTypeFactory().constructCollectionType(List.class, MainBean.class));
    truckService.saveData(itemsFromController);

    return new ModelAndView("redirect:/main");
}

ObjectMapper 来自jackson library

import com.fasterxml.jackson.databind.ObjectMapper;

[编辑]:

创建您在java中创建的相同模型:

var mainBean = {
    name: "",
    truckList: [],
    address: {}
}

然后您可以传递这样的值:

mainBean.address.houseNumber = $("#houseNumber").val();

在Javascript中创建模型后,您可以将其置于ajax调用

data : JSON.stringify(mainBean)