如何将表单字段集合发布到 Spring 控制器?
假设我有这样的表单:
<form method="post" action="/create">
<input type="text" name="title.0" value="Curious George" />
<input type="text" name="author.0" value="H.A. Rey" />
<input type="text" name="date.0" value="2/23/1973" />
<input type="text" name="title.1" value="Code Complete" />
<input type="text" name="author.1" value="Steve McConnell" />
<input type="text" name="date.1" value="6/9/2004" />
<input type="text" name="title.2" value="The Two Towers" />
<input type="text" name="author.2" value="JRR Tolkien" />
<input type="text" name="date.2" value="6/1/2005" />
<input type="submit" />
</form>
How do I parse this from a Spring MVC 3.0 controller?
Suppose I have form such as this:
<form method="post" action="/create">
<input type="text" name="title.0" value="Curious George" />
<input type="text" name="author.0" value="H.A. Rey" />
<input type="text" name="date.0" value="2/23/1973" />
<input type="text" name="title.1" value="Code Complete" />
<input type="text" name="author.1" value="Steve McConnell" />
<input type="text" name="date.1" value="6/9/2004" />
<input type="text" name="title.2" value="The Two Towers" />
<input type="text" name="author.2" value="JRR Tolkien" />
<input type="text" name="date.2" value="6/1/2005" />
<input type="submit" />
</form>
How do I parse this from a Spring MVC 3.0 controller?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
name
属性不必是唯一的。所以:然后
根据规范,应保留元素的顺序:
The
name
attribute need not be unique. So:And then
The order of the elements should be preserved, according to the spec:
如果您可以更改视图,理想情况下您可以使用某种列表来执行此操作。
类似于:
您将有一个包含 3 个元素的 Book 类。
和一个包含书籍列表的包含类 BookContainer
现在在你的控制器中,你将有一个
@ModelAttribute
方法,它返回要绑定的 Containing 类:最后你您的请求映射方法有一个 @ModelAttribute 参数:
spring 会根据您的需要自动将尽可能多的“书籍”添加到您的列表中。
If you can change the view, ideally you'd do this with some kind of list.
Something like:
you would have a Book class containing your 3 elements.
and a containing class which contains a list of books BookContainer
Now in your controller, you'd have a
@ModelAttribute
method which returns the Containing class to to bind to:finally you'd have a @ModelAttribute parameter to your request mapping method:
spring will automatically add as many 'Book's to your list as you need.
您的控制器请求映射可以简单地采用 spring WebRequest 作为参数,然后执行如下操作:
Could your controller request mapping simply take a spring WebRequest as the parameter and then do something like: