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

来源:互联网 发布:外国知乎瞧不起中国 编辑:程序博客网 时间:2024/05/21 09:53

在使用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"/> 

换种写法

<mvc:annotation-driven>    <mvc:message-converters>        <bean class="org.springframework.http.converter.StringHttpMessageConverter">            <constructor-arg value="UTF-8"/>        </bean>    </mvc:message-converters></mvc:annotation-driven>

拓展:
spring mvc在绑定表单之前,都会先注册这些编辑器,Spring自己提供了大量的实现类,诸如CustomDateEditor ,CustomBooleanEditor,CustomNumberEditor等许多,基本上够用。
使用时候调用WebDataBinder的registerCustomEditor方法
registerCustomEditor源码:

public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) {    getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor);}

第一个参数requiredType是需要转化的类型。
第二个参数PropertyEditor是属性编辑器,它是个接口,以上提到的如CustomDateEditor等都是继承了实现了这个接口的PropertyEditorSupport类。
我们也可以不使用他们自带的这些编辑器类。
我们可以自己构造:

import org.springframework.beans.propertyeditors.PropertiesEditor;public class DoubleEditor extends PropertyEditorSupport {    @Override    public void setAsText(String text) throws IllegalArgumentException {        if (text == null || text.equals("")) {            text = "0";        }        setValue(Double.parseDouble(text));    }    @Override    public String getAsText() {        return getValue().toString();    }}
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 橡筋裤头太紧了怎么办 内增高鞋跟太高怎么办 电脑增高架高了怎么办 银行取钱走后回来说少了怎么办 运动t桖太大了怎么办 袖口松紧太紧了怎么办 衣服穿着就皱了怎么办 麻料的衣服很皱怎么办 麻料衣服皱了怎么办 棉麻裤子皱了怎么办 裙子屁股坐皱了怎么办 真丝衣服洗皱了怎么办 粘纤的衣服皱了怎么办 硅胶手机壳粘灰怎么办 橡筋裤子买大了怎么办 橡筋裤子腰小了怎么办 地垫粘瓷砖上怎么办 汽车围裙锈透了怎么办 万能胶水沾到手上怎么办 圆领体恤领口容易皱怎么办 上衣剪了个洞怎么办 上衣破了个洞怎么办 鸟屎腐蚀车漆怎么办 毛风衣叠久了怎么办 黑色的衣服沾毛怎么办 雪纺裙子弄上油怎么办 内衣买小了怎么办妙招 长裤衬衫裙邹了怎么办 100棉衬衣皱了怎么办? 短袖t恤袖口大了怎么办 短袖底下卷边了怎么办 棉质短袖衫缩水怎么办 纯棉t恤缩水了怎么办 t恤缩水变小了怎么办 衣服掉在雨棚上怎么办 车衣密码锁忘记密码怎么办 衣服的铁拉链弯怎么办 去旅行衣服皱了怎么办 衣服抽绳出来了怎么办 裤子的绑带掉了怎么办 网纱裙的边卷了怎么办