• SpringMVC注解@initbinder解决类型转换问题


    在使用SpringMVC的时候,经常会遇到表单中的日期字符串和JavaBean的Date类型的转换,而SpringMVC默认不支持这个格式的转换,所以需要手动配置,自定义数据的绑定才能解决这个问题。
    在需要日期转换的Controller中使用SpringMVC的注解@initbinder和Spring自带的WebDateBinder类来操作。
    WebDataBinder是用来绑定请求参数到指定的属性编辑器.由于前台传到controller里的值是String类型的,当往Model里Set这个值的时候,如果set的这个属性是个对象,Spring就会去找到对应的editor进行转换,然后再SET进去。
    @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, 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"/> 
  • 相关阅读:
    20150128-堆雪人
    20150127-梦里笑醒的声音
    20150126-渡口
    20150125-阴天
    FastAdmin 的上传代码在哪里?
    在 Linux 安装 IIS?
    FastAdmin env.sample 的用法
    可以方便配合 Git 的现代编辑器
    运算放大器复习
    Linux 权限使用 777 真的好吗?
  • 原文地址:https://www.cnblogs.com/libo199374/p/8203389.html
Copyright © 2020-2023  润新知