SpringMVC中向服务器传递时间参数时出现的问题

原文地址: https://www.cnblogs.com/linux-wangkun/p/5691701.html

1. 问题描述:

  今天在SpringMVC应用中上传参数的时候遇到如下问题:

The request sent by the client was syntactically incorrect 

  这说明在提交的参数中,有的参数不符合服务器端数据要求。在排除其它参数没问题的情况下,确定是其中的时间参数除了问题。

  客户端传送的时间参数如下所示:

  

  而接受此参数的字段是一个Date类型的数据:

  

  在Controller中使用自动装箱:

  

  原因所在: 在装箱过程中时间的参数的转化出错。

2. 问题解决

  2.1 方法一:

    在需要转变时间的Controller中添加如下代码:

复制代码
@InitBinder
protected void initBinder(HttpServletRequest request,
            ServletRequestDataBinder binder) throws Exception {
    // DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    CustomDateEditor dateEditor = new CustomDateEditor(format, true);
    binder.registerCustomEditor(Date.class, dateEditor);
    super.initBinder(request, binder);
}
复制代码

 

  2.2 方法二:

    在实体类中对应的时间字段上加上如下注释:

@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;

    用这种方法的时候注意要引入joda-time.jar包,在Maven工程的pom.xml文件中加入如下依赖:

    

        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.4</version>
        </dependency>

猜你喜欢

转载自blog.csdn.net/xujingcheng123/article/details/80757535