Spring 3表单绑定对象始终为null

发布于 2024-10-18 21:14:49 字数 849 浏览 0 评论 0原文

我正在尝试将嵌套对象与 Spring 3 绑定,但遇到了问题。

JSP:

<portlet:actionURL var="formAction" />
<form:form id="add-objects-form" method="post" action="${formAction}">
   <input name = "obj.a"...>
   <input name = "obj.b"...>
   <input type = "file" multiple="multiple" name="file"/>
</form>

表单对象:

class FormObject{
private final static Logger logger = ...

private MultipartFile file
private Obj obj

...getters and setters
}

控制器:

@RequestMapping(method = RequestMethod.POST)
public void uploadDocument(@ModelAttribute FormObject formObject, BindingResult results ) {

}

formObject 获取 obj.aobj.b,但file始终为空。

I'm trying to bind a nested object with Spring 3, and I'm having issues.

JSP:

<portlet:actionURL var="formAction" />
<form:form id="add-objects-form" method="post" action="${formAction}">
   <input name = "obj.a"...>
   <input name = "obj.b"...>
   <input type = "file" multiple="multiple" name="file"/>
</form>

Form Object:

class FormObject{
private final static Logger logger = ...

private MultipartFile file
private Obj obj

...getters and setters
}

Controller:

@RequestMapping(method = RequestMethod.POST)
public void uploadDocument(@ModelAttribute FormObject formObject, BindingResult results ) {

}

formObject gets obj.a and obj.b, but file is always null.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

茶花眉 2024-10-25 21:14:49

中添加 modelAttribute="formObject"

还要确保您没有从类中排除调试信息。如果您已经或不确定,请指定 @ModelAttribute("formObject")

对于处理文件(多部分数据),您需要指定表单的 enctype:

enctype="multipart/form-data"

更新:因为您使用的是 js-文件上传库,具体操作如下:

  • 仅使用 ajax 请求上传图片(不要提交其他任何内容)。将上传的文件存储在临时位置,
  • 响应可能包含临时文件的名称。将这些名称存储在隐藏字段中
  • ,然后提交表单(通过 ajax 或通过常规提交),并传递隐藏字段的值,该值现在仅包含字符串
  • 从临时位置移动到永久位置
  • 将文件 已上传,但未提交表单,可以通过某些每小时/每日作业进行清理。

Add modelAttribute="formObject" in <form:form>

Also make sure you haven't excluded debug information from classes. If you have, or you are uncertain, specify @ModelAttribute("formObject")

For handling files (multipart data) you need to specify the enctype for the form:

enctype="multipart/form-data"

Update: since you are using a js-library for fileupload, here's what to do:

  • upload only picture with ajax request (don't submit anything else). Store the uploaded files in a temporary location
  • the response will possibly contain the names of the temp files. Store these names in a hidden field
  • then submit the form (either via ajax or via regular submit), and pass the value of the hidden field, which now contains only strings
  • move the files from the temporary location to a permanent location
  • files that have been uploaded, but without the form being submitted, can be cleaned by some hourly/daily job.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文