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"/> 
  • 相关阅读:
    在mac上搭建python环境
    iOS开发-你真的会用SDWebImage?(转发)
    iOS tableview 优化总结
    Masonry 实现输入框随键盘位置改变
    sudo 权限问题
    nodejs save遇到的一个坑
    iOS app的webview注入JS遇到的坑
    HW18-广搜
    HW17-深搜
    HW16-动归2
  • 原文地址:https://www.cnblogs.com/libo199374/p/8203389.html
Copyright © 2011-2022 走看看