java Spring MVC 和 jquery 使用 POJO 数组发布请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14459171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring MVC and jquery post request with array of POJO
提问by VladislavLysov
I have a simple POJO Java class (getters and setters is not shown)
我有一个简单的 POJO Java 类(未显示 getter 和 setter)
public class VacationInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Temporal(TemporalType.TIMESTAMP)
private Date vacationFrom;
@Temporal(TemporalType.TIMESTAMP)
private Date vacationTo;
, Spring MVC controller with next method
, Spring MVC 控制器与 next 方法
@RequestMapping(value = "updateVacations", method = RequestMethod.POST)
public String updateVacations(@RequestParam VacationInfo[] vacationInfos) {
...
}
and jQuery post request
和 jQuery 发布请求
$.ajax({
type: "POST",
url: "updateVacations",
dataType: 'json',
data: vacationInfos
});
where "vacationInfos" is a array with JSON objects, which represent VacationInfo class:
其中“vacationInfos”是一个包含 JSON 对象的数组,代表 VacationInfo 类:
[
{
vacationFrom: "01-01-2013",
vacationTo: "01-01-2013"
},
{
vacationFrom: "01-01-2013",
vacationTo: "01-01-2013"
}
]
But when I do request - i got a HTTP 400 error.
但是当我请求时 - 我收到了 HTTP 400 错误。
回答by Ravi Kant
This code is written to get all the form's which are checked and post them all to Spring controller
编写此代码是为了获取所有已检查的表单并将它们全部发布到 Spring 控制器
jquery method::
jquery方法::
$('#testButton').click(function(){
var testList= [];
$('.submit').filter(':checked').each(function() {
var checkedFrom= $(this).closest('form');
var testPojo= checkedFrom.serializeObject();
testList.push(testPojo);
});
$.ajax({
'type': 'POST',
'url':"testMethod",
'contentType': 'application/json',
'data': JSON.stringify(testList),
'dataType': 'json',
success: function(data) {
if (data == 'SUCCESS')
{
alert(data);
}
else
{
alert(data);
}
}
});
});
whereas jquery provide two level's of serialization like serialize() and serializeArray().But this is custome method for serialize a
而 jquery 提供了两个级别的序列化,如 serialize() 和 serializeArray()。但这是序列化 a 的自定义方法
User defined Object.
用户定义的对象。
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
in spring controller
在弹簧控制器中
@RequestMapping(value = "/testMethod", method = RequestMethod.POST)
public @ResponseBody ResponseStatus testMethod(HttpServletRequest request,
@RequestBody TestList testList)
throws Exception {
..............
}
where TestList is an another class which is written to handle form post with a array of Test in mvc controller for test method
其中 TestList 是另一个类,它被编写为在 mvc 控制器中为测试方法处理带有 Test 数组的表单发布
public class TestList extends ArrayList<Test> {}
回答by Anton Khaladok
You can create your own formatter to parse incoming request. Read ">here. The code below is a little trimmed.
您可以创建自己的格式化程序来解析传入的请求。">在这里阅读。下面的代码略有删减。
public class LinkFormatter implements Formatter<List<Link>> {
@Override
public List<Link> parse(String linksStr, Locale locale) throws ParseException {
return new ObjectMapper().readValue(linksStr, new TypeReference<List<Link>>() {});
}
}
Jquery:
查询:
$.ajax({
type: "POST",
data: JSON.stringify(collection)
...
});
Spring controller:
弹簧控制器:
@RequestParam List<Link> links
And don't forget to register it in application context:
并且不要忘记在应用程序上下文中注册它:
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<set>
<bean class="LinkFormatter"/>
</set>
</property>
回答by Vinay
try using @RequestBody
instead of @RequestParam
尝试使用@RequestBody
代替@RequestParam
@RequestMapping(value = "updateVacations", method = RequestMethod.POST)
public String updateVacations(@RequestBody VacationInfo[] vacationInfos) {
...
}
The @RequestBody
method parameter annotation indicates that a method parameter should be bound to the value of the HTTP request body, which is the JSON data in your case.
所述@RequestBody
方法参数注释指示方法参数应绑定到HTTP请求的身体,这是你的情况JSON数据的值。
回答by VladislavLysov
I answered my question. Form client I send Date as timestamp. Because server should not know anything about what time zone is the client and should not depend on a specific date format(it's one of the best practice). And after that I'm add JsonDeserializer annotation on VacationInfo date fields and this is work.
我回答了我的问题。表单客户端我发送日期作为时间戳。因为服务器不应该知道客户端是什么时区,并且不应该依赖于特定的日期格式(这是最佳实践之一)。之后我在 VacationInfo 日期字段上添加 JsonDeserializer 注释,这是工作。
public class VacationInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonDeserialize(using=DateDeserializer.class)
@Temporal(TemporalType.TIMESTAMP)
private Date vacationFrom;
@JsonDeserialize(using=DateDeserializer.class)
@Temporal(TemporalType.TIMESTAMP)
private Date vacationTo;
Ajax POST request
Ajax POST 请求
[
{
vacationFrom: "1359197567033",
vacationTo: "1359197567043"
},
{
vacationFrom: "1359197567033",
vacationTo: "1359197567043"
}
]
If you need to send Date as string in specific format("mm-dd-yyyy" for example) - you need to define own JsonDesiarilizer(org.codehaus.Hymanson.map package in Hymanson) class, which extends frpm JsonDeserializer class and implement your logic.
如果您需要发送日期为字符串在特定的格式(“MM-DD-YYYY”为例) -你需要定义自己的JsonDesiarilizer(org.codehaus.Hymanson.map包Hyman逊)类,它扩展了FRPM JsonDeserializer类,并实现你的逻辑。