英文:
Post DTO to Spring Controller, parameters are null
问题
Front end:
let bemsidList = new Array();
bemsidList[0] = "3129426";
bemsidList[1] = "240540";
let postData = { bemsids: bemsidList };
var xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/delete-email", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
postData
}));
Wrapper:
public class EmailWrapper {
List<String> bemsids;
public List<String> getBemsids() {
return bemsids;
}
public void setBemsids(List<String> bemsids) {
this.bemsids = bemsids;
}
}
Controller:
@RequestMapping(
value = "/admin/delete-email",
method = RequestMethod.POST,
consumes = "application/json")
public String deleteEmail(@RequestBody EmailWrapper wrapper, Model model) {
List<String> ids = wrapper.getBemsids();
for (String s : ids) {
EmailEntity emailEntity = emailRepository.findByOwnerBemsid(s);
emailRepository.delete(emailEntity);
}
model.addAttribute("category", "admin");
model.addAttribute("subCategory", "email");
return "pages/index";
}
Debug - Breakpoint:
Breakpoint reveals getBemsids
is null:
ids
is null:
英文:
I am trying to Post a list of strings from my Javascript front end to a Spring Boot Controller, for some reason the post happens, but my values are null. Is there anything obviously wrong with my code?
Front end:
let bemsidList = new Array()
bemsidList[0] = "3129426";
bemsidList[1] = "240540";
let postData = { bemsids: bemsidList};
var xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/delete-email", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
postData
}));
Wrapper:
public class EmailWrapper {
List<String> bemsids;
public List<String> getBemsids() {
return bemsids;
}
public void setBemsids(List<String> bemsids) {
this.bemsids = bemsids;
}
}
Controller:
@RequestMapping(
value = "/admin/delete-email",
method = RequestMethod.POST,
consumes = "application/json")
public String deleteEmail(@RequestBody EmailWrapper wrapper, Model model) {
List<String> ids = wrapper.getBemsids();
for (String s : ids) {
EmailEntity emailEntity = emailRepository.findByOwnerBemsid(s);
emailRepository.delete(emailEntity);
}
model.addAttribute("category", "admin");
model.addAttribute("subCategory", "email");
return "pages/index";
}
Debug - Breakpoint:
答案1
得分: 1
Annotation @RequestBody
用于 RESTful 应用程序,@ModelAttribute
用于 Web MVC。您正在混淆这两者,这就是问题所在。您可以尝试将 @RequestBody
改为 @ModelAttribute
,并且使用表单数据代替 XHR 请求从前端发送数据。
英文:
Annotation requestbody is used for restful applications & modelattribute for web mvc..you are mixing both and that is the issue here. Can you try changing requestbody with modelattribute and use form data instead xhr request to send data from frontend.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论