首页 > 解决方案 > 模型属性为空

问题描述

我用弹簧靴2

控制器部分

@PostMapping("template/new/samplings")
@ResponseBody
public SamplingsDto save(@ModelAttribute SamplingsDto samplings) {
    return samplingsService.save(samplings);
}

我尝试保存表格

$("#samplingsForm").submit(function (e){
    e.preventDefault();

    var receptionDate =  $("#samplingsReceptionDatePicker").data('daterangepicker').startDate.format('YYYY-MM-DD');
    var buildDate =  $("#samplingsBuildDatePicker").data('daterangepicker').startDate.format('YYYY-MM-DD');

    var form = transForm.serialize('#samplingsForm');

    form.receptionDate=receptionDate;
    form.buildDate=buildDate;

    form = JSON.stringify(form);

    $.ajax({
        type:"post",
        url: "/template/new/samplings",
        data: form,
        contentType: "application/json",
        dataType : "json",
        success: function(data){
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });

});

使用 chrome 请求有效负载是

"{" "samplingsId":"", "buildDate":"2018-06-20", "receptionDate":"2018-06-20", "productTypesId":"1", "productsId":"15", “}”

在服务器模型属性字段为空

编辑

public class SamplingsDto {

        private Integer samplingsId;

        private Integer productTypesId;

        private Integer productsId;

        private LocalDate receptionDate;

        private LocalDate buildDate;

        //get set
    }

标签: javaajaxspring-mvcspring-boot

解决方案


首先,为 SamplingsDto 的属性添加 setter 和 getter。(我也会将 Lombok 用于 setter/getter)

public class SamplingsDto {
    private Integer samplingsId;

    private Integer productTypesId;

    private Integer productsId;

    private LocalDate receptionDate;

    private LocalDate buildDate;

    public Integer getSamplingsId() {
        return samplingsId;
    }

    public void setSamplingsId(Integer samplingsId) {
        this.samplingsId = samplingsId;
    }

    public Integer getProductTypesId() {
        return productTypesId;
    }

    public void setProductTypesId(Integer productTypesId) {
        this.productTypesId = productTypesId;
    }

    public Integer getProductsId() {
        return productsId;
    }

    public void setProductsId(Integer productsId) {
        this.productsId = productsId;
    }

    public LocalDate getReceptionDate() {
        return receptionDate;
    }

    public void setReceptionDate(LocalDate receptionDate) {
        this.receptionDate = receptionDate;
    }

    public LocalDate getBuildDate() {
        return buildDate;
    }

    public void setBuildDate(LocalDate buildDate) {
        this.buildDate = buildDate;
    }
}

然后你可以按如下方式使用它:

@PostMapping("template/new/samplings")
public SamplingsDto save(@RequestBody SamplingsDto samplings) {
    return samplingsService.save(samplings);
}

推荐阅读