spring mvc4使用及json 日期转换解决方案
spring mvc使用注解方式配制,以及对rest风格的支持,真是完美致极。
下面将这两天研究到的问题做个总结,供参考。
1.request对象的获取
方式1:在controller方法上加入request参数,spring会自动注入,如:public String list(HttpServletRequest request,HttpServletResponse response)
方式2:在controller类中加入@Resource private HttpServletRequest request 属性,spring会自动注入,这样不知道会不会出现线程问题,因为一个controller实例会为多个请求服务,暂未测试。
方式3:在controller方法中直接写代码获取 HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
方式4:在controller中加入以下方法,此方法会在执行此controller的处理方法之前执行
- @ModelAttribute
- private void initServlet(HttpServletRequest request,HttpServletResponse response) {
- //String p=request.getParameter("p");
- //this.req=request;//实例变量,有线程安全问题,可以使用ThreadLocal模式保存
- }
2.response对象的获取
可以参照以上request的获取方式1和方式4,方式2和方式3对response对象无效!
3.表单提交之数据填充
直接在方法上加入实体对象参数,spring会自动填充对象中的属性,对象属性名要与<input>的name一致才会填充,如:public boolean doAdd(Demo demo)
4.表单提交之数据转换-Date类型
在实体类的属性或get方法上加入 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss"),那么表单中的日期字符串就会正确的转换为Date类型了。还有@NumberFormat注解,暂时没用,就不介绍了,一看就知道是对数字转换用的。
5.json数据返回
在方法上加入@ResponseBody,同时方法返回值为实体对象,spring会自动将对象转换为json格式,并返回到客户端。如下所示:
- @RequestMapping("/json1")
- @ResponseBody
- public Demo json1() {
- Demo demo=new Demo();
- demo.setBirthday(new Date());
- demo.setCreateTime(new Date());
- demo.setHeight(170);
- demo.setName("tomcat");
- demo.setRemark("json测试");
- demo.setStatus((short)1);
- return demo;
- }
注意:spring配置文件要加上:<mvc:annotation-driven/>,同时还要引入jackson-core.jar,jackson-databind.jar,jackson-annotations.jar(2.x的包)才会自动转换json
这种方式是spring提供的,我们还可以自定义输出json,以上第二条不是说了获取response对象吗,拿到response对象后,任由开发人员宰割,想怎么返回就怎么返回。
方法不要有返回值,如下:
- @RequestMapping("/json2")
- public void json2() {
- Demo demo=new Demo();
- demo.setBirthday(new Date());
- demo.setCreateTime(new Date());
- demo.setHeight(170);
- demo.setName("tomcat");
- demo.setRemark("json测试");
- demo.setStatus((short)1);
- String json=JsonUtil.toJson(obj);//;json处理工具类
- HttpServletResponse response = //获取response对象
- response.getWriter().print(json);
- }
OK,一切很完美。接着恶心的问题迎面而来,date类型转换为json字符串时,返回的是long time值,如果你想返回“yyyy-MM-dd HH:mm:ss”格式的字符串,又要自定义了。我很奇怪,不是有@DateTimeFormat注解吗,为什么不利用它。难道@DateTimeFormat只在表单提交时,将字符串转换为date类型,而date类型转换为json字符串时,就不用了。带着疑惑查源码,原来spring使用jackson转换json字符,而@DateTimeFormat是spring-context包中的类,jackson如何转换,spring不方便作过多干涉,于是只能遵守jackson的转换规则,自定义日期转换器。
先写一个日期转换器,如下:
- public class JsonDateSerializer extends JsonSerializer<Date> {
- private SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- @Override
- public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
- throws IOException, JsonProcessingException {
- String value = dateFormat.format(date);
- gen.writeString(value);
- }
- }
在实体类的get方法上配置使用转换器,如下:
- @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
- @JsonSerialize(using=JsonDateSerializer.class)
- public Date getCreateTime() {
- return this.createTime;
- }
OK,到此搞定。
你真的满意了吗,这么不优雅的解决方案,假设birthday属性是这样的,只有年月日,无时分秒
- @DateTimeFormat(pattern="yyyy-MM-dd")
- public Date getBirthday() {
- return this.birthday;
- }
这意味着,又要为它定制一个JsonDate2Serializer的转换器,然后配置上,像这样
- @DateTimeFormat(pattern="yyyy-MM-dd")
- @JsonSerialize(using=JsonDate2Serializer.class)
- public Date getBirthday() {
- return this.birthday;
- }
假设还有其它格式的Date字段,还得要为它定制另一个转换器。my god,请饶恕我的罪过,不要让我那么难受
经过分析源码,找到一个不错的方案,此方案将不再使用@JsonSerialize,而只利用@DateTimeFormat配置日期格式,jackson就可以正确转换,但@DateTimeFormat只能配置在get方法上,这也没什么关系。
先引入以下类,此类对jackson的ObjectMapper类做了注解扫描拦截,使它也能对加了@DateTimeFormat的get方法应用日期格式化规则
- package com.xxx.utils;
- import java.io.IOException;
- import java.lang.reflect.AnnotatedElement;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import org.springframework.format.annotation.DateTimeFormat;
- import org.springframework.stereotype.Component;
- import com.fasterxml.jackson.core.JsonGenerator;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.JsonSerializer;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.fasterxml.jackson.databind.SerializerProvider;
- import com.fasterxml.jackson.databind.introspect.Annotated;
- import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
- import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
- /**
- * json处理工具类
- * @author zhangle
- */
- @Component
- public class JsonUtil {
- private static final String DEFAULT_DATE_FORMAT="yyyy-MM-dd HH:mm:ss";
- private static final ObjectMapper mapper;
- public ObjectMapper getMapper() {
- return mapper;
- }
- static {
- SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
- mapper = new ObjectMapper();
- mapper.setDateFormat(dateFormat);
- mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
- @Override
- public Object findSerializer(Annotated a) {
- if(a instanceof AnnotatedMethod) {
- AnnotatedElement m=a.getAnnotated();
- DateTimeFormat an=m.getAnnotation(DateTimeFormat.class);
- if(an!=null) {
- if(!DEFAULT_DATE_FORMAT.equals(an.pattern())) {
- return new JsonDateSerializer(an.pattern());
- }
- }
- }
- return super.findSerializer(a);
- }
- });
- }
- public static String toJson(Object obj) {
- try {
- return mapper.writeValueAsString(obj);
- } catch (Exception e) {
- throw new RuntimeException("转换json字符失败!");
- }
- }
- public <T> T toObject(String json,Class<T> clazz) {
- try {
- return mapper.readValue(json, clazz);
- } catch (IOException e) {
- throw new RuntimeException("将json字符转换为对象时失败!");
- }
- }
- public static class JsonDateSerializer extends JsonSerializer<Date>{
- private SimpleDateFormat dateFormat;
- public JsonDateSerializer(String format) {
- dateFormat = new SimpleDateFormat(format);
- }
- @Override
- public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
- throws IOException, JsonProcessingException {
- String value = dateFormat.format(date);
- gen.writeString(value);
- }
- }
- }
再将<mvc:annotation-driven/>改为以下配置,配置一个新的json转换器,将它的ObjectMapper对象设置为JsonUtil中的objectMapper对象,此转换器比spring内置的json转换器优先级更高,所以与json有关的转换,spring会优先使用它。
- <mvc:annotation-driven>
- <mvc:message-converters>
- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
- <property name="objectMapper" value="#{jsonUtil.mapper}"/>
- <property name="supportedMediaTypes">
- <list>
- <value>text/json;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- </mvc:message-converters>
- </mvc:annotation-driven>
接下来就可以这样配置实体类,jackson也能正确转换Date类型
- @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
- public Date getCreateTime() {
- return this.createTime;
- }
- @DateTimeFormat(pattern="yyyy-MM-dd")
- public Date getBirthday() {
- return this.birthday;
- }
完毕,一切都完美了。
以下为2014/4/21 补充
写了那么多,发现白忙活了一场,原来jackson也有一个@JsonFormat注解,将它配置到Date类型的get方法上后,jackson就会按照配置的格式转换日期类型,而不自定义转换器类,欲哭无泪啊。辛苦了那么多,其实别人早已提供,只是没有发现而已。
不说了,直接上方案吧。
1.spring配置照样是这样:
- <mvc:annotation-driven>
2.JsonUtil可以不用了,但如果要自己从response对象输出json,那么还是可以用,但改成了这样
- package com.xxx.utils;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import org.springframework.stereotype.Component;
- import com.fasterxml.jackson.databind.ObjectMapper;
- /**
- * json处理工具类
- * @author zhangle
- */
- @Component
- public class JsonUtil {
- private static final String DEFAULT_DATE_FORMAT="yyyy-MM-dd HH:mm:ss";
- private static final ObjectMapper mapper;
- static {
- SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
- mapper = new ObjectMapper();
- mapper.setDateFormat(dateFormat);
- }
- public static String toJson(Object obj) {
- try {
- return mapper.writeValueAsString(obj);
- } catch (Exception e) {
- throw new RuntimeException("转换json字符失败!");
- }
- }
- public <t> T toObject(String json,Class<t> clazz) {
- try {
- return mapper.readValue(json, clazz);
- } catch (IOException e) {
- throw new RuntimeException("将json字符转换为对象时失败!");
- }
- }
- }</t></t>
3.实体类的get方法就需要多一个@JsonFormat的注解配置
- @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;
- }
- @DateTimeFormat(pattern="yyyy-MM-dd")
- @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
- public Date getBirthday() {
- return this.birthday;
- }
spring mvc4使用及json 日期转换解决方案的更多相关文章
- spring mvc 使用及json 日期转换解决方案
http://blog.csdn.net/z69183787/article/details/40375479
- json日期转换
//调用 ChangeDateFormat(CreatTime) //json日期转换 function ChangeDateFormat(jsondate) { jsondate = jsondat ...
- Newtonsoft.Json日期转换
在使用EasyUI做后台时,使用表格datagrid,用Newtonsoft.Json转换为Json格式后,时间显示为2013-06-15 T00:00:00形式. 后来研究了一下Newtonsoft ...
- [Spring MVC] 表单提交日期转换问题,比如可能导致封装实体类时400错误
三种格式的InitBinder @InitBinder//https://stackoverflow.com/questions/20616319/the-request-sent-by-the-cl ...
- json日期格式问题的办法
//json日期转换 格式(2015-01-01) <input class="easyui-datebox" name="sbdj_txtShebaoka_Lin ...
- java中json和字符串互转及日期转换 练习
一:以下是用到的jar名称: commons-beanutils-1.6.jar commons-collections-3.2.1.jar commons-lang-2.6.jar commons- ...
- Struts2、Spring MVC4 框架下的ajax统一异常处理
本文算是struts2 异常处理3板斧.spring mvc4:异常处理 后续篇章,普通页面出错后可以跳到统一的错误处理页面,但是ajax就不行了,ajax的本意就是不让当前页面发生跳转,仅局部刷新, ...
- SpringMVC配置全局日期转换器,处理日期转换异常
Spring 3.1.1使用Mvc配置全局日期转换器,处理日期转换异常链接地址: https://www.2cto.com/kf/201308/236837.html spring3.0配置日期转换可 ...
- 个人永久性免费-Excel催化剂功能第90波-xml与json数据结构转换表格结构
在网络时代,大量的数据交互以xml和json格式提供,特别是系统间的数据交互和网络WebAPI.WebService接口的数据提供,都是通过结构化的xml或json提供给其他应用调用返回数据.若能提供 ...
随机推荐
- Java注解--实现简单读取excel
实现工具类 利用注解实现简单的excel数据读取,利用注解对类的属性和excel中的表头映射,使用Apache的poi就不用在业务代码中涉及row,rows这些属性了. 定义注解: @Retentio ...
- iOS 实现简单的毛玻璃效果
最近在整理导航栏的渐隐渐现效果,整理过程中偶然学会了图片的毛玻璃效果实现,很简单,不多说了,先上图看看效果对比, 这是原图, 这是加了效果后的,创建图片的代码就不上了,下面看下添加效果的代码: // ...
- ReactiveObjC使用
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 20.0px Menlo; color: #78492a; background-color: #fffff ...
- Ext ApplicationController&ref的使用
Ext ApplicationController&ref的使用 Ext.define('app.controller.ApplicationController', { //继承 Ext.a ...
- Java添加JDBC
添加JDBC 1.SQL Server SQL Server2005 下载 sqljdbc_4.0 https://www.microsoft.com/en-us/download/details.a ...
- Android Studio 运行java程序
当我们装了Android Studio 学习安卓开发的时候,难免会要学习java,这时候,难道在重新装一个编译器吗?不需要,我们直接用 Android Studio 就可以. 1.新建一个空项目,选择 ...
- 深入理解Java虚拟机-----------虚拟机类加载机制
虚拟机类加载机制 类从被加载到虚拟机内存开始,到卸载出内存为止,整个生命周期包括:加载,验证,准备,解析,初始化,使用,卸载等7个阶段.其中,验证,准备,解析3个部分称为连接. 以上7个阶段中,加载, ...
- Google调试工具
f11 逐语句,到过程里,f10逐过程,跳到下一个off,f8调到下一个断点执行.
- 流行框架(angularj基础)
- P1280 尼克的任务
题目描述 尼克每天上班之前都连接上英特网,接收他的上司发来的邮件,这些邮件包含了尼克主管的部门当天要完成的全部任务,每个任务由一个开始时刻与一个持续时间构成. 尼克的一个工作日为N分钟,从第一分钟开始 ...