javaspringjspspring-mvcjspx

Spring controller get empty object


I'm sending an object to spring controller via jsp form.

JSP:

<form:form modelAttribute="uploadItem" action="/uploadObject" method="post" enctype="multipart/form-data">

<form:input path="fileData" accept="audio/mpeg" type="file" id="file-upload" name="file-upload" />

<form:input type="text" path="title" id="upload-title" name="upload-title"/>

<input type="image" src="..." alt="Upload"/>

</form:form>

ModelService:

 public void fillUploadMelodyModel(Model model) {
    fillAdminRootModel(model);
    model.addAttribute("uploadItem", new UploadedItem());
}

UploadedItem:

public class UploadedItem {
  private CommonsMultipartFile fileData;
  private String title;
}

Controller:

 @RequestMapping(value = "/uploadObject", method = RequestMethod.POST)
    public String doUpload(UploadedItem uploadItem, BindingResult result, Principal principal) {
//at this point I get an empty object (null null values)
}

What is the problem? How to pass object to controller in jsp?


Solution

  • Try changing then your controller like this

    @RequestMapping(value = "/uploadObject", method = RequestMethod.POST)
    public String doUpload(UploadedItem uploadItem, 
                          BindingResult result, 
                          @RequestParam("fileData") MultipartFile file,
                          @RequestParam("title") String title,
                          Principal principal) {
    //Here you should receive your parameters
    }