简体   繁体   English

Spring MVC和jQuery发布带有POJO数组的请求

[英]Spring MVC and jquery post request with array of POJO

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控制器的下一种方法

@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错误。

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()。但这是用于序列化一个的定制方法

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

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请求正文的值,在您的情况下为HTTP数据。

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.jackson.map package in Jackson ) class, which extends frpm JsonDeserializer class and implement your logic. 如果您需要以特定格式(例如“ mm-dd-yyyy”)以字符串形式发送Date-您需要定义自己的JsonDesiarilizer( Jackson中的 org.codehaus.jackson.map包)类,该类扩展了frpm JsonDeserializer类并实现你的逻辑。

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: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM