zoukankan      html  css  js  c++  java
  • springMVC注解@initbinder日期类型的属性自动转换

    在实际操作中经常会碰到表单中的日期 字符串和Javabean中的日期类型的属性自动转换, 而springMVC默认不支持这个格式的转换,所以必须要手动配置, 自定义数据类型的绑定才能实现这个功能。

    一、控制器中代码

    比较简单的可以直接应用springMVC的注解@initbinder和spring自带的WebDataBinder类和操作,controller中配置了initBinder()时则再接收String型的日期时会自动转换

    package com.shiliu.game.controller;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.springframework.beans.propertyeditors.CustomDateEditor;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.annotation.InitBinder;
    
    public class InitController {
    
        /**
         * 自动转换日期类型的字段格式
         */
        @InitBinder
        public void initBinder(WebDataBinder binder) {
                 
             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
             binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
         }
    }

     二、springMVC中配置

        <!-- 解析器注册 -->
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
            <property name="messageConverters">
                <list>
                    <ref bean="stringHttpMessageConverter" />
                </list>
            </property>
        </bean>
        <!-- String类型解析器,允许直接返回String类型的消息 -->
        <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/html; charset=utf-8</value>
                </list>
            </property>
        </bean>

     此篇内容参考:http://blog.csdn.net/jiubugeinifo/article/details/41678717

  • 相关阅读:
    吃货联盟项目
    字串符笔记
    带有参的方法
    js:自动亮起100盏灯
    JS字面量创建方式的优缺点
    为什么说对象字面量赋值比new Object()高效?
    javascript 字面量
    vue学习(一)、Vue.js简介
    Redis(二):c#连接Redis
    Redis(一):centos下安装。
  • 原文地址:https://www.cnblogs.com/wkrbky/p/6093794.html
Copyright © 2011-2022 走看看