前端本来有四个
将他们封装到addcloseportForm中,统一传入后端,通过mapper写入数据库
前端传入后端的方法
addboxmessage() {
this.$refs.addFormRef.validate(async (valid) => {
if (!valid) return;
const { data: res } = await this.$http.post(
"addboxmessage",
this.addcloseportForm
);
if (res != "success") {
return this.$message.error("操作失败");
}
this.$message.success("操作成功");
});
},
但是在后端controller接受的时候,一直都有两个是空的。
后端函数和System.out.println结果
@RequestMapping("/addboxmessage")
public String addboxmessage(@RequestBody BoxMessage boxmessage){
System.out.println(boxmessage);
int i = bmdao.addboxmessage(boxmessage);
return i >0?"success":"error";
}
其中的boxType和LeadSeal一直显示的是null
由于认为是先输出boxmessage的,所以一开始认为是前端有问题或者前端传到后端的过程有问题
在前端调试,利用
console.log(this.addcloseportForm.boxType);
console.log(this.addcloseportForm.LeadSeal);
进行调试,在控制台发现可以正确输出
问题的解决
此处最大的问题是对前后端交互的流程不够了解
最终发现是在后端的Bean中未给这两个字段赋予getter、setter方法
当赋予getter和setter方法后,发现boxType可以写入数据库中了,但是LeadSeal还是Null
重新进入Bean中观察,发现由于LeadSeal的首字母是大写L,他的构造方法、getter和setter方法和别的不太一样
构造方法
public BoxMessage(String boxid, String orderid, String boxType, String leadSeal) {
this.boxid = boxid;
this.orderid = orderid;
this.boxType = boxType;
LeadSeal = leadSeal;
}
常规的getter、setter和首字母大写的LeadSeal的方法对比
public String getBoxType() {
return boxType;
}
public void setBoxType(String boxType) {
this.boxType = boxType;
}
public String getLeadSeal() {
return LeadSeal;
}
public void setLeadSeal(String leadSeal) {
LeadSeal = leadSeal;
}
此处考虑将LeadSeal改为leadSeal试试,得到了新的构造方法和getter、setter
public BoxMessage(String boxid, String orderid, String boxType, String leadSeal) {
this.boxid = boxid;
this.orderid = orderid;
this.boxType = boxType;
this.leadSeal = leadSeal;
}
public String getLeadSeal() {
return leadSeal;
}
public void setLeadSeal(String leadSeal) {
this.leadSeal = leadSeal;
}
最终成功输出
数据库也成功写入
总结
在Java后端的Bean中,声明变量的时候,首字母不要大写,可以避免这样setter的错误。