Spring MVC JSON自定义类型转换(续)

简介:

通过配置全局的日期转换来避免使用麻烦的注解。


首先用到了一个简单的日期工具类DateUtil.java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * DateUtil类 
  3.  * 
  4.  * @author liuzh 
  5.  */  
  6. public class DateUtil {  
  7.   
  8.     public static final String Y_M_D = "yyyy-MM-dd";  
  9.     public static final String Y_M_D_HM = "yyyy-MM-dd HH:mm";  
  10.     public static final String Y_M_D_HMS = "yyyy-MM-dd HH:mm:ss";  
  11.     public static final String YMD = "yyyyMMdd";  
  12.     public static final String YMDHM = "yyyyMMddHHmm";  
  13.     public static final String YMDHMS = "yyyyMMddHHmmss";  
  14.     public static final String ymd = "yyyy/MM/dd";  
  15.     public static final String ymd_HM = "yyyy/MM/dd HH:mm";  
  16.     public static final String ymd_HMS = "yyyy/MM/dd HH:mm:ss";  
  17.   
  18.     /** 
  19.      * 智能转换日期 
  20.      * 
  21.      * @param date 
  22.      * @return 
  23.      */  
  24.     public static String smartFormat(Date date) {  
  25.         String dateStr = null;  
  26.         if (date == null) {  
  27.             dateStr = "";  
  28.         } else {  
  29.             try {  
  30.                 dateStr = formatDate(date, Y_M_D_HMS);  
  31.                 //时分秒  
  32.                 if (dateStr.endsWith(" 00:00:00")) {  
  33.                     dateStr = dateStr.substring(010);  
  34.                 }  
  35.                 //时分  
  36.                 else if (dateStr.endsWith("00:00")) {  
  37.                     dateStr = dateStr.substring(016);  
  38.                 }  
  39.                 //秒  
  40.                 else if (dateStr.endsWith(":00")) {  
  41.                     dateStr = dateStr.substring(016);  
  42.                 }  
  43.             } catch (Exception ex) {  
  44.                 throw new IllegalArgumentException("转换日期失败: " + ex.getMessage(), ex);  
  45.             }  
  46.         }  
  47.         return dateStr;  
  48.     }  
  49.   
  50.     /** 
  51.      * 智能转换日期 
  52.      * 
  53.      * @param text 
  54.      * @return 
  55.      */  
  56.     public static Date smartFormat(String text) {  
  57.         Date date = null;  
  58.         try {  
  59.             if (text == null || text.length() == 0) {  
  60.                 date = null;  
  61.             } else if (text.length() == 10) {  
  62.                 date = formatStringToDate(text, Y_M_D);  
  63.             } else if (text.length() == 13) {  
  64.                 date = new Date(Long.parseLong(text));  
  65.             } else if (text.length() == 16) {  
  66.                 date = formatStringToDate(text, Y_M_D_HM);  
  67.             } else if (text.length() == 19) {  
  68.                 date = formatStringToDate(text, Y_M_D_HMS);  
  69.             } else {  
  70.                 throw new IllegalArgumentException("日期长度不符合要求!");  
  71.             }  
  72.         } catch (Exception e) {  
  73.             throw new IllegalArgumentException("日期转换失败!");  
  74.         }  
  75.         return date;  
  76.     }  
  77.   
  78.     /** 
  79.      * 获取当前日期 
  80.      * @param format 
  81.      * @return 
  82.      * @throws Exception 
  83.      */  
  84.     public static String getNow(String format) throws Exception{  
  85.         return formatDate(new Date(), format);  
  86.     }  
  87.   
  88.     /** 
  89.      * 格式化日期格式 
  90.      * 
  91.      * @param argDate 
  92.      * @param argFormat 
  93.      * @return 格式化后的日期字符串 
  94.      */  
  95.     public static String formatDate(Date argDate, String argFormat) throws Exception {  
  96.         if (argDate == null) {  
  97.             throw new Exception("参数[日期]不能为空!");  
  98.         }  
  99.         if (StringUtils.isEmpty(argFormat)) {  
  100.             argFormat = Y_M_D;  
  101.         }  
  102.         SimpleDateFormat sdfFrom = new SimpleDateFormat(argFormat);  
  103.         return sdfFrom.format(argDate).toString();  
  104.     }  
  105.   
  106.     /** 
  107.      * 把字符串格式化成日期 
  108.      * 
  109.      * @param argDateStr 
  110.      * @param argFormat 
  111.      * @return 
  112.      */  
  113.     public static Date formatStringToDate(String argDateStr, String argFormat) throws Exception {  
  114.         if (argDateStr == null || argDateStr.trim().length() < 1) {  
  115.             throw new Exception("参数[日期]不能为空!");  
  116.         }  
  117.         String strFormat = argFormat;  
  118.         if (StringUtils.isEmpty(strFormat)) {  
  119.             strFormat = Y_M_D;  
  120.             if (argDateStr.length() > 16) {  
  121.                 strFormat = Y_M_D_HMS;  
  122.             } else if (argDateStr.length() > 10) {  
  123.                 strFormat = Y_M_D_HM;  
  124.             }  
  125.         }  
  126.         SimpleDateFormat sdfFormat = new SimpleDateFormat(strFormat);  
  127.         //严格模式  
  128.         sdfFormat.setLenient(false);  
  129.         try {  
  130.             return sdfFormat.parse(argDateStr);  
  131.         } catch (ParseException e) {  
  132.             throw new Exception(e);  
  133.         }  
  134.     }  
  135. }  

需要用到的是两个智能转换日期的方法。关于转换的格式和规则,请看这两个方法,如果不符合你需要的,可以自行修改。


然后继承SimpleDateFormat写一个智能转换日期的类SmartDateFormat

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * Description: 智能日期转换 
  3.  * Author: liuzh 
  4.  */  
  5. public class SmartDateFormat extends SimpleDateFormat {  
  6.     @Override  
  7.     public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {  
  8.         return new StringBuffer(DateUtil.smartFormat(date));  
  9.     }  
  10.   
  11.     @Override  
  12.     public Date parse(String text) throws ParseException {  
  13.         return DateUtil.smartFormat(text);  
  14.     }  
  15. }  
这里重写了两个方法,这两个方法是互相转换的方法,直接调用的DateUtil提供的两个智能转换的方法。


最后在Spring MVC的xml中配置:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
  2.   <property name="objectMapper">  
  3.     <bean class="org.codehaus.jackson.map.ObjectMapper">  
  4.       <property name="dateFormat">  
  5.         <!-- 智能日期转换 -->  
  6.         <bean class="packageName.SmartDateFormat"/>  
  7.       </property>  
  8.     </bean>  
  9.   </property>  
  10. </bean>  
这段代码主要是针对MappingJacksonHttpMessageConverter进行配置。经过这样的配置之后,Spring就能自动根据日期样式进行转换了。


至于“智能”转换,完全就是简单的if/else判断,可以查看最上面的代码。

目录
相关文章
|
1月前
|
缓存 前端开发 Java
Spring MVC 面试题及答案整理,最新面试题
Spring MVC 面试题及答案整理,最新面试题
90 0
|
1月前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
26 0
|
1月前
|
SQL Java 数据库连接
挺详细的spring+springmvc+mybatis配置整合|含源代码
挺详细的spring+springmvc+mybatis配置整合|含源代码
42 1
|
12天前
|
数据采集 前端开发 Java
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
23 3
|
12天前
|
存储 前端开发 Java
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
14 1
|
12天前
|
前端开发 Java Spring
数据之桥:深入Spring MVC中传递数据给视图的实用指南
数据之桥:深入Spring MVC中传递数据给视图的实用指南
29 3
|
22天前
|
前端开发 安全 Java
使用Java Web框架:Spring MVC的全面指南
【4月更文挑战第3天】Spring MVC是Spring框架的一部分,用于构建高效、模块化的Web应用。它基于MVC模式,支持多种视图技术。核心概念包括DispatcherServlet(前端控制器)、HandlerMapping(请求映射)、Controller(处理请求)、ViewResolver(视图解析)和ModelAndView(模型和视图容器)。开发流程涉及配置DispatcherServlet、定义Controller、创建View、处理数据、绑定模型和异常处理。
使用Java Web框架:Spring MVC的全面指南
|
28天前
|
敏捷开发 监控 前端开发
Spring+SpringMVC+Mybatis的分布式敏捷开发系统架构
Spring+SpringMVC+Mybatis的分布式敏捷开发系统架构
66 0
|
4月前
|
设计模式 前端开发 JavaScript
Spring MVC(一)【什么是Spring MVC】
Spring MVC(一)【什么是Spring MVC】
|
1月前
|
Java Apache vr&ar
springmvc报错 nested exception is org.mybatis.spring.MyBatisSystemException:
springmvc报错 nested exception is org.mybatis.spring.MyBatisSystemException:
16 0