SpringMVC接收日期类型参数

在开发过程中遇到了这个问题,在网上找了很多相关的解决办法
参考这篇:http://m.blog.csdn.net/u013041642/article/details/74923650讲的很详细,但是我没有成功。

一般类型的参数,都会自动实现转换,如下的pojo类

@Component
public class UserAuthorize {
    private Integer id;

    private Integer userId;

    private Integer identityType;

    private String identifier;

    private String credential;
}

在controller中

    /**
     *
     * @param userAuthorize 
     * @return
     */
    @RequestMapping(value = "***.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<UserBase> updateUserInformation(UserAuthorize  userAuthorize ) {
    }

前端提交参数就会被自动绑定到userAuthorize对应的字段中

但是,如果UserAuthorize类中有个字段是Date类型,就会出现如下错误:

The request sent by the client was syntactically incorrect.

因为时间类型没有对应转换规则的话,服务器就会报错。

再参考这篇:http://m.blog.csdn.net/qq_14952009/article/details/46651927就成功了。

最简单的解决办法就是在对应的类属性上加上注解,如下:

@Component
public class UserAuthorize {
    private Integer id;

    private Integer userId;

    private Integer identityType;

    private String identifier;

    private String credential;

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

pattern的规则自己定,但是前端在提交参数的时候必须和该规则一致,我这里,前端就需要提交date=2018-1-5。

还有很多其他的解决办法,看了很多,这个是最简单的了。

猜你喜欢

转载自blog.csdn.net/qq_16403141/article/details/78983080