在做web开发的时候,页面传入的都是String类型,SpringMVC可以对一些基本的类型进行转换,但是对于日期类的转换可能就需要我们配置。

1、如果查询类使我们自己写,那么在属性前面加上@DateTimeFormat(pattern = "yyyy-MM-dd")  ,即可将String转换为Date类型,如下

1
2
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createTime;

2、如果我们只负责web层的开发,就需要在controller中加入数据绑定:

1
2
3
4
5
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); //true:允许输入空值,false:不能为空值

3、可以在系统中加入一个全局类型转换器

实现转换器

1
2
3
4
5
6
7
8
9
10
11
12
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
 dateFormat.setLenient(false);
 try {
  return dateFormat.parse(source);
 } catch (ParseException e) {
  e.printStackTrace();
 }  
 return null;
}

进行配置:

1
2
3
4
5
6
7
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
  <property name="converters">
   <list>
    <bean class="com.doje.XXX.web.DateConverter" />
   </list>
  </property>
</bean>
1
<mvc:annotation-driven conversion-service="conversionService" />

4、如果将日期类型转换为String在页面上显示,需要配合一些前端的技巧进行处理。

5、SpringMVC使用@ResponseBody返回json时,日期格式默认显示为时间戳。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component("customObjectMapper")
public class CustomObjectMapper extends ObjectMapper {
  
 public CustomObjectMapper() {
  CustomSerializerFactory factory = new CustomSerializerFactory();
  factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {
   @Override
   public void serialize(Date value, JsonGenerator jsonGenerator,
     SerializerProvider provider) throws IOException, JsonProcessingException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    jsonGenerator.writeString(sdf.format(value));
   }
  });
  this.setSerializerFactory(factory);
 }
}

配置如下:

1
2
3
4
5
6
7
<mvc:annotation-driven>
 <mvc:message-converters>
  <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
   <property name="objectMapper" ref="customObjectMapper"></property>
  </bean>
 </mvc:message-converters>
</mvc:annotation-driven>

6、date类型转换为json字符串时,返回的是long time值,如果需要返回指定的日期的类型的get方法上写上@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") ,即可将json返回的对象为指定的类型。

1
2
3
4
5
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
public Date getCreateTime() {
return this.createTime;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

通过注解来协助SpringMVC处理日期在前后端的传递问题

从前端向后端传递日期:

@DateTimeFormat(pattern="yyyy-MM-dd")

前台向后台传递字符串类型的日期参数时,需要通过此注解将字符串解析成日期类型,其中日期格式可以根据需要进行设置。

例子:如果后台接收的createDate为Java.util.Date类型,但前台传递过来的是2016-05-23,那么此时我们需要使用@DateTimeFormat注解来修饰createDate字段,否则SpringMVC认为传递过来的是字符串与日期类型不匹配而报400错误(HTTP Status 400 The request sent by the client was syntactically incorrect)。

从后端向前端传递日期:

@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")

SpringMVC向前端返回json格式的数据时,日期类型默认返回时间戳,那么我们可以通过此注解将时间返回为固定格式的字符串。
使用此注解需要引入一下jar包(需要特别注意的是jackson最新的版本对此功能不兼容,因此建议选择2.6.1或者以下的版本):

    1. <dependency>
    2. <groupId>org.codehaus.jackson</groupId>
    3. <artifactId>jackson-mapper-asl</artifactId>
    4. <version>1.9.13</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>com.fasterxml.jackson.core</groupId>
    8. <artifactId>jackson-core</artifactId>
    9. <version>2.6.1</version>
    10. </dependency>
    11. <dependency>
    12. <groupId>com.fasterxml.jackson.core</groupId>
    13. <artifactId>jackson-databind</artifactId>
    14. <version>2.6.1</version>
    15. </dependency>

本文转自http://blog.csdn.net/kylinah/article/details/53101068 感谢作者

spring mvc日期转换(前端到后端,后端到前端)的更多相关文章

  1. Spring MVC对象转换说明

    在Spring MVC之前我们需要在Servlet里处理HttpServletRequest参数对象,但这个对象里的属性都是通用类型的对象(如字符串),处理起来很繁琐并且容易出错,而Spring MV ...

  2. spring boot日期转换

    spring boot 作为微服务简易架构.拥有其自身的特点.快速搭建架构 简单 快捷.这里我只是简单的介绍下我遇到的其中的  两个问题.第一前台页面传递的时间类型 无法自动映射到Java的 Date ...

  3. Spring mvc 时间转换

    http://www.cnblogs.com/ssslinppp/p/4600043.html

  4. Spring MVC前后端的数据传输

    本篇文章主要介绍了Spring MVC中如何在前后端传输数据. 后端 ➡ 前端 在Spring MVC中这主要通过Model将数据从后端传送到前端,一般的写法为: @RequestMapping(va ...

  5. Spring MVC教程——检视阅读

    Spring MVC教程--检视阅读 参考 Spring MVC教程--一点--蓝本 Spring MVC教程--c语言中午网--3.0版本太老了 Spring MVC教程--易百--4.0版本不是通 ...

  6. 基于Vue+Spring MVC+MyBatis+Shiro+Dubbo开发的分布式后台管理系统

    本文项目代码: 服务端:https://github.com/lining90567/dubbo-demo-server 前端:https://github.com/lining90567/dubbo ...

  7. SSM(spring mvc+spring+mybatis)学习路径——2-1、spring MVC入门

    目录 2-1 Spring MVC起步 一.回顾Servlet 二.SpringMVC简介 三.搭建SpringMVC第一个案例 四.简单流程及配置 五.使用注解开发Controller 六.参数绑定 ...

  8. spring + spring mvc + tomcat 面试题(史上最全)

    文章很长,而且持续更新,建议收藏起来,慢慢读! 高并发 发烧友社群:疯狂创客圈(总入口) 奉上以下珍贵的学习资源: 疯狂创客圈 经典图书 : 极致经典 + 社群大片好评 < Java 高并发 三 ...

  9. Java之Spring mvc详解

    文章大纲 一.Spring mvc介绍二.Spring mvc代码实战三.项目源码下载四.参考文章   一.Spring mvc介绍 1. 什么是springmvc   springmvc是sprin ...

随机推荐

  1. JSON使用讲解

    前端操作json  一.JSON字符串与JSON对象的区别 1. 一个对象以“{”  开始,     “}”结束.   每个“名称”后跟一个“:”(冒号):“‘名称/值’ 对”之间运用 “,”(逗号) ...

  2. 最简单的SPA(单页应用)实现

    $(function(){ var replacePage = function(href, onFinish){ $.get(href,{},function(raw){ var data = ra ...

  3. PHP语言开发Paypal支付demo的具体实现

    如果我们的应用是面向国际的.那么支付的时候通常会考虑使用paypal.以下为个人写的一个paypal支付示例,已亲测可行.paypal有个很不错的地方就是为开发者提供了sandbox(沙箱)测试功能. ...

  4. Elasticsearch--地理搜索

    目录 地理位置索引 空间搜索映射定义 示例 基于距离的排序 边界框过滤 距离的限制 任意地理形状搜索 点 包络线 多边形 多个多边形 把形状保存到索引中 地理位置索引 空间搜索映射定义 elastic ...

  5. python计算auc指标

    1.安装scikit-learn 1.1Scikit-learn 依赖 Python (>= 2.7 or >= 3.3), NumPy (>= 1.8.2), SciPy (> ...

  6. 创建一个TCP服务器端通信程序的步骤

    创建一个TCP服务器端通信程序的步骤: 1). 创建一个ServerSocket 2). 从ServerSocket接受客户连接请求 3). 创建一个服务线程处理新的连接 4). 在服务线程中,从so ...

  7. 在WEB项目中调用QQ通讯组件打开QQ聊天界面

    在很多WEB项目中,需要提供在线服务的功能,加上自己的联系方式,例如:QQ,不用添加QQ好友也可以交谈,那这到底是怎么实现的呢? 对于这个功能,需要提到一个组件,即“QQ通讯组件”.QQ通讯组件是一种 ...

  8. SpringMVC-Mybatis整合和注解开发

    SpringMVC-Mybatis整合和注解开发SpringMVC-Mybatis整合整合的思路在mybatis和spring整合的基础上 添加springmvc.spring要管理springmvc ...

  9. bzoj 4026 dC Loves Number Theory 主席树+欧拉函数

    题目描述 dC 在秒了BZOJ 上所有的数论题后,感觉萌萌哒,想出了这么一道水题,来拯救日益枯竭的水题资源.给定一个长度为 n的正整数序列A,有q次询问,每次询问一段区间内所有元素乘积的φ(φ(n)代 ...

  10. 06二叉树、Map、Collections、适配器

    06二叉树.Map.Collections.适配器-2018/07/16 1.set集合,无索引,不可以重复,无序(存取不一致) 2.TreeSet用来对象元素进行排序,可以保证元素唯一 储存自定义对 ...