Skip to content
Advertisement

Post DTO to Spring Controller, parameters are 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:

breakpoint reveals getBemsids is null

ids is null

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement