zoukankan      html  css  js  c++  java
  • 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"/> 
  • 相关阅读:
    v-cloak无效解决方法
    堆栈,托管堆,堆,栈的区别
    2018-3-25至2018-8-9的日语笔记
    windows下远程连接redis
    windows cmd打开共享文件夹
    C#数据分组
    安装pyspider遇到的坑
    argument 1 must be 2-item sequence, not int
    python,pip环境变量设置
    python编程学习--Pygame
  • 原文地址:https://www.cnblogs.com/libo199374/p/8203389.html
Copyright © 2011-2022 走看看