springmvc基础知识(6):PropertyEditor应用

  • 在开启SpringMVC容器的时候,会注册一些默认的属性编辑器,这些编辑器定义了一些属性类型的转换,对于不同的类型,有相应的属性编辑器与之绑定。这就组成了一些基本的属性转换器。
  • 对于这些默认的属性转换器,如果不符合我们的预期,可以进行修改。

局部属性编辑器

  • 处理方法:
@RequestMapping("/propertyEditor.do")
public String dateFormat(Date birthday){
    System.out.println(birthday);
    return "success";
}

这里使用系统默认,只要传递过来的字符串按照一定的格式就可以进行转换,但是这里我们不按照系统默认的格式进行传输。

  • 提交的表单:
<form action="propertyEditor.do">
    用户名 :<input type="text" name="userName">
    生日:<input type="text" name="birthday">
    <button type="submit">提交</button>
</form>

这里写图片描述
报错
这里写图片描述

这时候,在处理方法所在类中自定义一个时间属性编辑器:

/**
 * 时间属性编辑器
 */
@InitBinder
public void initBinder(DataBinder bin){
    //定义格式化
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    //定制一个时间属性编辑器
    CustomDateEditor cust = new CustomDateEditor(sdf, true);
    //将这个属性编辑器绑定到Date类型上
    bin.registerCustomEditor(Date.class,cust);
}

再执行:
执行成功并跳转到success.jsp页面
这里写图片描述

  • Spring为我们提供了大量的编辑器实现类,诸如
    CustomDateEditor,CustomBooleanEditor,CustomNumberEditor等都是继承自PropertyEditorSupport类。
  • 使用时候调用DataBinder的registerCustomEditor方法进行注册。
  • 或者使用DataBinder的子类WebDataBinder进行注册。一般开发会使用WebDataBinder多些

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();
    }
}

@InitBinder 可以指定value,如果不指定则为所有的相关类型参数进行添加自定义编辑器。 如果指定,则是为指定的参数添加。如:
@InitBinder(“data1”) 为属性名称为data1的参数添加自定义的属性编辑器。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值