java - JQ Ajax应该选择Json还是Json字符串向后端传递比较合适?

查看:168
本文介绍了java - JQ Ajax应该选择Json还是Json字符串向后端传递比较合适?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

比如说,现在需求是希望把前端的数据传向SpringMVC,绑定在请求方法的一个实体参数中

@Request(value="test", method=RequestMethod.POST) @ResponseBody
public String test(TwoDate td) {
    return td.toString();
}

其中,TwoDate是那个实体类,有两个被@DateTimeFormat所标记的Date类型的私有域。

1、我尝试了一下以下的方式

$.ajax({
    type:"post",
    url:"/test",
    data:saveData,
    success:function(data) {
        alert(data);
    },
    error:function(data) {
        alert('error');
    }
});

没有问题,前端的saveData成功绑定到了TwoDate td中。

2、随后,我换了以下的方式

    $.ajax({
        type:"post",
        url:"/test",
        dataType:"json",
        contentType : 'application/json',
        data:JSON.stringify(saveData),
        success:function(data) {
            alert(data);
        },
        error:function(data) {
            alert('error');
        }
    });

并在请求方法的参数前面追加了个@RequestBody 注解,
报了HTTP-400错误,控制台提示我

org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpMessageNotReadable
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize value of type java.util.Date from String "2017-01-01 02:03:04": not a valid representation (error: Failed to parse Date value '2017-01-01 02:03:04': Can not parse date "2017-01-01 02:03:04Z": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null))

非常奇怪,而当我把实体类的两个域的类型从Date改成String后,又正常了

3、我的dispatcherservlet.xml的配置关于消息转换的配置是这样的

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class = "org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            </bean>
            <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

所以我想问一下,实际开发中,向后端传递JSON字符串是否更合适?
JSON字符串有办法绑定到含有Date类型的实体中吗?
如果没有办法,那么大家的做法是否是将这些Date类型换成String类型吗?

不胜感激:)

解决方案

类似这样:

url: "${pageContext.request.contextPath}/test.html",
data:{
    customerIdTypeCode:'test',
    customerIdNo:'123456',
    customerName:'test',
        orderNo:'test'
    },
type: "POST",
dataType: "json",

关于后台接收参数,可以用对象封装,类似这样:

@RequestMapping(value = "/checkClient", method = RequestMethod.POST)
@ResponseBody
public TransferConfirmationSaveResult checkClient(CustomerForm customerForm){
   // do something
}

关于CustomerForm 就是一个普通的POJO类:

import java.io.Serializable;

public class CustomerForm implements Serializable {

    private static final long serialVersionUID = 8884979226377423802L;

    /**
     * 订单编号
     */
    private String orderNo;
    /**
     * 客户名称
     */
    private String customerName;
    /**
     * 客户类型代码
     */
    private String customerTypeCode;
    /**
     * 证件号码
     */
    private String customerIdNo;
  
    .... getter/setter ....
    
    
}

关于Date的问题,spring mvc有各种处理办法做数据处理,举个栗子:
可以创建一个BaseController,然后所有Controller都继承BaseController,如下处理就可以用Date来接收日期型数据

package com.xiatianlong.controller;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.text.SimpleDateFormat;
import java.util.Date;

public class BaseController {

    /**
     * 数据绑定
     *
     * @param binder
     *            WebDataBinder
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
    }
    
}

这篇关于java - JQ Ajax应该选择Json还是Json字符串向后端传递比较合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆