我使用Spring Boot 2
Controller 部分
@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
}
最佳答案
首先,为 SamplingsDto 的属性添加 setter 和 getter。 (我还会使用 Lombok 作为 setter/getters)
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);
}
关于java - 模型属性为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50956050/