• SpringMVC日期类型转换问题三大处理方法


    在SpringMVC开发中,可能遇到比较多的问题就是前台与后台实体类之间日期转换处理的问题了,说问题也不大,但很多人开发中经常会遇到这个问题,有时很令人头疼,有时间问题暴露的不是很明显,然后逐渐对问题进行跟踪,会发现是日期类型转换失败“映射”不到对应的持久类的日期属性上造成的。

    现总结归纳出一下解决这个问题的三大方法;

    方法一:实体类中加日期格式化注解

    [java] view plain copy
     
    1. @DateTimeFormat(pattern = "yyyy-MM-dd")  
    2. private Date receiveAppTime;  

    如上,在对应的属性上,加上指定日期格式的注解

    方法二:控制器Action中加入一段数据绑定代码

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


    方法三:实现一个全局日期类型转换器并进行配置

    此方法较为复杂,请详细查看另一篇博文:SpringMVC配置全局日期转换器,处理日期转换异常

    附加方法四:适合页面把日期类型转换成字符串且JSP,Freemark页面

    JSP模版引擎方法:

    [java] view plain copy
     
    1. <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>   
    2. <fmt:formatDate value="${job.jobtime }" pattern="yyyy-MM-dd HH:mm:ss"/>  

    Freemarker模版引擎方法:

    [java] view plain copy
     
      1. <input id="receiveAppTime" name="receiveAppTime" type="text" value="${(bean.receiveAppTime?string('yyyy-MM-dd'))!}" /> 
  • 相关阅读:
    出错处理函数abort、exit、atexit、strerror. . .
    linux查询系统信息命令
    [转载]比google和百度强十倍的搜索类网站
    陶  朱  商  经
    ip的划分,超详细.【网管常识】
    linux的hostname修改详解
    勤于寻找谈话资料
    Windows常用命令集
    C语言中printf格式
    How to disable SELinux
  • 原文地址:https://www.cnblogs.com/tanzq/p/8451226.html
Copyright © 2020-2023  润新知