SpingMVC -@InitBinder与日期的格式化

来源:互联网 发布:亚洲蹲 知乎 编辑:程序博客网 时间:2024/06/18 18:03

由@InitBinder标识的方法,可以对WebDataBinder对象进行初始化(于目标方法执行前执行!!)。
WebDataBinder是DataBinder的子类,用于完成由表单字段到JavaBean属性的绑定。

以下为WebDataBinder的注释:

Special DataBinder for data binding from web request parameters to JavaBean objects.--将请求参数绑定到JavaBean 对象(这就是主要功能!!!)--因为方法参数Employee employee 为Java bean ,所以需要使用binder!!! Designed for web environments, but not dependent on the Servlet API;  serves as base class for more specific DataBinder variants,  such as org.springframework.web.bind.ServletRequestDataBinder. 

需要注意的是:
① @InitBinder方法不能有返回值,它必须声明为void;
② @InitBinder方法的参数通常是WebDataBinder;


【1】@InitBinder日期转换示例:

    @InitBinder    public void initBinder(WebDataBinder binder) {        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        dateFormat.setLenient(false);        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));    }
      • 该方法常用于表单–对象的日期属性的类型转换!!!

【2】使用xml配置自定义日期转换器

springmvc.xml:

 <!-- 注册处理器映射器/处理器适配器 ,添加conversion-service属性-->    <mvc:annotation-driven conversion-service="conversionService"/>    <!-- 创建conversionService,并注入dateConvert-->    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">        <property name="converters">            <set>                <ref bean="dateConvert"/>            </set>        </property>    </bean>    <!-- 创建自定义日期转换规则 -->    <bean id="dateConvert" class="com.web.convert.DateConvert"/>
  • 自定义日期转换器如下:
public class DateConvert implements Converter<String, Date> {    public Date convert(String s) {        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        try {            return simpleDateFormat.parse(s);        } catch (ParseException e) {            e.printStackTrace();        }        return null;    }}
0 0