SpringMVC日期类型转换问题——SpringMVC配置全局日期转换器 SpringMVC配置全局日期转换器

今天在练习springmvc前端到后台数据映射的时候出现了The request sent by the client was syntactically incorrect.错误,找了好半天才发现是前端日期是字符串类型的,传到后台时,后台的Java程序不能将字符串日期解释成Date类型的日期;因此这里需要在springmvc中配置全局日期转换器,下面是我从网上找的一些帖子。

转载链接点击打开链接

前言

        我们在SpringMVC开发中,可能遇到比较多的问题就是前台与后台实体类之间日期转换处理的问题了,说问题也不大,但很多人开发中经常会遇到这个问题,有时很令人头疼,有时间问题暴露的不是很明显,然后逐渐对问题进行跟踪,会发现是日期类型转换失败“映射”不到对应的持久类的日期属性上造成的,由此我还特意写过一篇博文:SpringMVC中出现" 400 Bad Request "错误(用@ResponseBody处理ajax传过来的json数据转成bean)的解决方法。感兴趣的码农可以看一看,总结了常见造成springMVC出现“400 Bad Request”错误的七大原因,其中就有前台的字符串日期类型与后台的java日期类型匹配不上造成的。

       今天晚上呢,特意抽出宝贵的时间来总结归纳出一下解决这个问题的三大方法,分享给大家,以帮助更多像我一样的人。鄙人不才,如果过程中有讲解的不清或者不对的地方,还望认真阅读的您,留下你的宝贵意见或建议,以便您,我,还有大家更快更好的共同进步!

       好了,我们切入正题吧!

 

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

[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.classnew 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'))!}" />  


SpringMVC配置全局日期转换器

spring3.0配置日期转换可以通过配置自定义实现WebBingingInitializer接口的一个日期转换类来实现,方法如下

1、转换类:

package stu.kx.util;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Create by 康茜 on 2018/5/20.
 *
 * spring3.0配置日期转换可以通过配置自定义实现WebBingingInitializer接口的一个日期转换类来实现
 */
public class DateEnride implements WebBindingInitializer {
    @Override
    public void initBinder(WebDataBinder webDataBinder, WebRequest webRequest) {
        //设置从前端获取的日期格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //将这种日期格式与Java api Date进行转化
        //参数true表示这个date属性可以为空
        webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}

2、在springmvc.xml文件中进行如下配置

 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">    
        <!-- 日期格式转换 -->    
        <property name="webBindingInitializer">    
            <bean class="DateConverter" />    
        </property>    
    </bean>  

spring3.1.1的处理进行调整,所以按照3.0的写法在3.1.1里面是无效的,正确的写法如下

1、定义DateConverter类

package stu.kx.util;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Create by 康茜 on 2018/5/20.
 *
 * spring3.0之后的配置全局日期转换方式
 */
public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        try {
            return dateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

2、springmvc.xml文件中进行配置

 <!--配置注解处理器映射器-->
    <!--配置注解处理器适配器-->
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
    <!--配置自定义日期转换器,并且在mvc:annotation-driven 标签中加上conversion-service属性-->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="stu.kx.util.DateConverter"></bean>
            </list>
        </property>
    </bean>


猜你喜欢

转载自blog.csdn.net/kangxidagege/article/details/80386935