Yon*_*rni 4 forms spring-mvc deserialization
我正在尝试将一些数据从客户端发送到服务器,并将其处理为文件下载.我正在使用一个简单的HTML表单,因为我想初始化文件下载(而不是AJAX).其中一个表单字段是一个项目数组.(另外两个是名称和描述字符串).我在提交表单之前将此字段序列化为字符串(JSON.stringify).
在服务器端,我尝试了一百万种技术(@ModelAttribute与@RequestBody,不同的jackson映射bean配置),将其转换为单一类型或三种不同类型(String + String + List/Array).
我发现的例子只适用于AJAX ......任何人都可以提供一个工作示例或一个描述吗?
=======
更新:我已经通过JSON.stringify实现了一个变通方法并将其传递给其中一个输入,并且在服务器端我有:
@RequestMapping(method = RequestMethod.POST, value = "exportSectionsToExcel")
public HttpEntity<byte[]> createExcelWorkBook(@ModelAttribute ExportSectionsListForm exportSectionsListForm) {
Section[] sectionObjects = gson.fromJson(exportSectionsListForm.getSections(), Section[].class);
...
Run Code Online (Sandbox Code Playgroud)
使用仅包含字符串的ExportSectionsListForm对象:
public class ExportSectionsListForm {
private String name;
private String url;
private String rssUrl;
private String sections;
...
(omitting ctor, getters and setters)
Run Code Online (Sandbox Code Playgroud)
另外,我找到了这个有希望的链接:http: //viralpatel.net/blogs/spring-mvc-multi-row-submit-java-list/ 但是没试过 - 看起来我需要动态生成输入元素为了这个工作,但它实际上可能是正确的解决方案.有没有人试过这个?
@ModelAttribute标记将尝试基于表单发布构建对象.由于您将表单值序列化为JSON,因此无法正常工作.@RequestBody只是给你一个表示请求体的String.因此,您可以获取表示传入JSON的String,然后使用FlexJSON的Jackson(或您使用的任何JSON库)解组JSON.不过,我不确定这是最好的方法.
我会问为什么你需要将表单序列化为JSON才能开始.Spring可以很好地处理带有Lists/Maps的表单.只需使用@ModelAttribute提交表单,在Controller上创建"数组"和List,或任何您期望的内容.所以,如果我正确地解释你的例子,我的ModelAttribute看起来像:
public class ExportSectionsFormBean {
private String name;
private String url;
private String rssUrl;
private List<String> sections;
/* getters/setters */
}
Run Code Online (Sandbox Code Playgroud)
然后我的Controller方法看起来像:
@RequestMapping(method = RequestMethod.POST, value = "exportSectionsToExcel")
public HttpEntity<byte[]> createExcelWorkBook(@ModelAttribute ExportSectionsFormBean exportSectionsFormBean ) {
/* Do whatever with your */
}
Run Code Online (Sandbox Code Playgroud)
在表单方面,使用Spring JSTL标签,只需使"部分"字段看起来像:
<form:input path="sections[0]" />
<form:input path="sections[1]" />
Run Code Online (Sandbox Code Playgroud)
或者,如果您更愿意使用HTML,那么
<input type="text" name="sections[0]" id="sections0" />
<input type="text" name="sections[1]" id="sections1" />
Run Code Online (Sandbox Code Playgroud)
这是由上述JSTL标记生成的内容.只要"sections"的值作为' section [#] = value ' 放在HTTP请求中,就可以了.
| 归档时间: |
|
| 查看次数: |
17802 次 |
| 最近记录: |