Spring控制器获取空对象

时间:2017-01-30 14:12:33

标签: java spring jsp spring-mvc jspx

我通过jsp格式向Spring控制器发送一个对象。

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;
}

控制器:

 @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)
}

有什么问题?如何在jsp中将对象传递给控制器​​?

2 个答案:

答案 0 :(得分:2)

尝试按此更改控制器

@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
}

答案 1 :(得分:0)

我认为您用于文件(文件上传)和标题(上传标题)的名称与您的域对象属性名称不同步。在Jsp页面中将您的名字更改为fileData和title。