spring mvc 使用及json 日期转换解决方案

第一步:创建CustomObjectMapper类

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. /**  
  2.  * 解决SpringMVC使用@ResponseBody返回json时,日期格式默认显示为时间戳的问题。需配合<mvc:message-converters>使用  
  3.  *   
  4.  * @author hellostory  
  5.  * @date 2013-10-31 下午04:17:52  
  6.  */  
  7. @Component("customObjectMapper")  
  8. public class CustomObjectMapper extends ObjectMapper {  
  9.   
  10.     public CustomObjectMapper() {  
  11.         CustomSerializerFactory factory = new CustomSerializerFactory();  
  12.         factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {  
  13.             @Override  
  14.             public void serialize(Date value, JsonGenerator jsonGenerator,  
  15.                     SerializerProvider provider) throws IOException, JsonProcessingException {  
  16.                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  17.                 jsonGenerator.writeString(sdf.format(value));  
  18.             }  
  19.         });  
  20.         this.setSerializerFactory(factory);  
  21.     }  
  22. }  


第二步:配置如下:

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <mvc:annotation-driven>  
  2.     <mvc:message-converters>  
  3.         <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
  4.             <property name="objectMapper" ref="customObjectMapper"></property>  
  5.         </bean>  
  6.     </mvc:message-converters>  
  7. </mvc:annotation-driven>  

效果如下:

 

格式化前:


格式化后:



---------------------------------------------------- --------------------------------------------------------------------------------------------------------


又到搭新开发环境的时候,总是不免去网上搜下目前最新的框架。spring是web开发必用的框架,于是乎下载了目前最新的spring4.0.3,同时越来越不想用struts2,想试试spring mvc,也将spring-webmvc4.0.3下了下来,投入两天时间学习后,发现还是挺优雅的,特别是从3.0后,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的处理方法之前执行

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. @ModelAttribute  
  2. private void initServlet(HttpServletRequest request,HttpServletResponse response) {  
  3.     //String p=request.getParameter("p");  
  4.     //this.req=request;//实例变量,有线程安全问题,可以使用ThreadLocal模式保存  
  5. }  

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格式,并返回到客户端。如下所示:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. @RequestMapping("/json1")  
  2. @ResponseBody  
  3. public Demo json1() {  
  4.     Demo demo=new Demo();  
  5.     demo.setBirthday(new Date());  
  6.     demo.setCreateTime(new Date());  
  7.     demo.setHeight(170);  
  8.     demo.setName("tomcat");   
  9.     demo.setRemark("json测试");   
  10.     demo.setStatus((short)1);   
  11.     return demo;  
  12. }  
注意:spring配置文件要加上:<mvc:annotation-driven/>,同时还要引入jackson-core.jar,jackson-databind.jar,jackson-annotations.jar(2.x的包)才会自动转换json
这种方式是spring提供的,我们还可以自定义输出json,以上第二条不是说了获取response对象吗,拿到response对象后,任由开发人员宰割,想怎么返回就怎么返回。
方法不要有返回值,如下:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. @RequestMapping("/json2")  
  2. public void json2() {  
  3.     Demo demo=new Demo();  
  4.     demo.setBirthday(new Date());  
  5.     demo.setCreateTime(new Date());  
  6.     demo.setHeight(170);  
  7.     demo.setName("tomcat");  
  8.     demo.setRemark("json测试");  
  9.     demo.setStatus((short)1);  
  10.     String json=JsonUtil.toJson(obj);//;json处理工具类  
  11.     HttpServletResponse response = //获取response对象  
  12.     response.getWriter().print(json);  
  13. }  
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的转换规则,自定义日期转换器。
先写一个日期转换器,如下:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. public class JsonDateSerializer extends JsonSerializer<Date> {  
  2.    private SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  3.    @Override  
  4.    public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)  
  5.            throws IOException, JsonProcessingException {  
  6.        String value = dateFormat.format(date);  
  7.        gen.writeString(value);  
  8.    }  
  9. }  
在实体类的get方法上配置使用转换器,如下:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")  
  2. @JsonSerialize(using=JsonDateSerializer.class)  
  3. public Date getCreateTime() {  
  4.     return this.createTime;  
  5. }  
OK,到此搞定。
你真的满意了吗,这么不优雅的解决方案,假设birthday属性是这样的,只有年月日,无时分秒
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. @DateTimeFormat(pattern="yyyy-MM-dd")  
  2. public Date getBirthday() {  
  3.     return this.birthday;  
  4. }  
这意味着,又要为它定制一个JsonDate 2 Serializer的转换器,然后配置上,像这样
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. @DateTimeFormat(pattern="yyyy-MM-dd")  
  2. @JsonSerialize(using=JsonDate2Serializer.class)  
  3. public Date getBirthday() {  
  4.     return this.birthday;  
  5. }  
假设还有其它格式的Date字段,还得要为它定制另一个转换器。my god,请饶恕我的罪过,不要让我那么难受
经过分析源码,找到一个不错的方案,此方案将不再使用@JsonSerialize,而只利用@DateTimeFormat配置日期格式,jackson就可以正确转换,但@DateTimeFormat只能配置在get方法上,这也没什么关系。
先引入以下类,此类对jackson的ObjectMapper类做了注解扫描拦截,使它也能对加了@DateTimeFormat的get方法应用日期格式化规则

猜你喜欢

转载自www.cnblogs.com/skinchqqhah/p/10350355.html