Spring mvc 日期转换器

Spring mvc 转换器(前台日期转换)

三种方式------

一。在pojo里 待转换的属性上打注解

@DateTimeFormat(pattern = “yyyy-MM-dd”)


二、web层开发使用@InitBinder注解

web层控制器中

FormHandleController控制器中添加注解:@InitBinder 
并且实现方法:public void initBinder(WebDataBinder binder) 

在其中实现注册日期编辑器

// web层  controller中 进行数据绑定  
    @InitBinder
    public void initBinder(WebDataBinder binder)
{        
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      // 严格限制日期转换       
      sdf.setLenient(false);
     //true:允许输入空值,false:不能为空值       
     binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));   
 }

三.在系统中加入一个全局类型转换器

全局类型转换器类

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

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

扫描二维码关注公众号,回复: 1520132 查看本文章


//  定义系统全局类型转换器
public class DateConverter implements Converter<String, Date>{
    @Override
    public Date convert(String source) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

 //设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01

        sdf.setLenient(false);
        try {
            return sdf.parse(source);
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }

}

注册到配置文件SpringMVC.xml中

<!-- 配置 全局日期类型转换器 -->
    <bean id="conversionService" 
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters" >
            <list>
                <bean class="com.wm.spring.MVC.service.DateConverter" />
            </list>
        </property>

    </bean>

注册到驱动中(handlerAdapter)

<!-- 配置全局日期类型转换器 -->        
    <mvc:annotation-driven conversion-service="conversionService" />

over  使用第一种和第三种  第二种不推荐使用!!!






猜你喜欢

转载自blog.csdn.net/weixin_41253479/article/details/80444538