SSM(Spring+SpringMVC+MyBatis)

SpringMVC-参数绑定(三)

2020-04-15  本文已影响0人  张明学

本篇文章主要介始PropertyEditor、Formatter、Converter的用法

PropertyEditor


PropertyEditor主要可以将一个字符串转换成目标对象(Controller形参的对象类型),PropertyEditor是一个接口,主要方法有:

void setValue(Object value);
Object getValue();
void setAsText(String text) throws java.lang.IllegalArgumentException;
...

使用的时候可以继承PropertyEditorSupport,如:

public class UserPropertyEditorSupport extends PropertyEditorSupport {

   @Override
   public void setAsText(String text) throws IllegalArgumentException {
       User user = new User();
       String[] propertys = text.split(",");
       user.setName(propertys[0]);
       user.setAge(Integer.valueOf(propertys[1]));
       this.setValue(user);
   }

   public static void main(String[] args) {
       UserPropertyEditorSupport userPropertyEditorSupport = new UserPropertyEditorSupport();
       userPropertyEditorSupport.setAsText("张三,18");
       // getValue() 返回的就是User对象
       System.out.println(userPropertyEditorSupport.getValue());
   }
}

在Controller中用法需要通过@InitBinder做注入,并且只在当前Controller中生效!

@RequestMapping("/test1")
    @ResponseBody
    public String test1(@RequestParam Date beginDate) {
        return "time=" + beginDate.getTime();
    }

    @InitBinder
    private void initDate(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

以上test1就可以通过http://127.0.0.1:8080/data-bind/test1?beginDate=2020-04-15访问。
跟踪WebDataBinder的registerCustomEditor,你会发现它调用的是:

org.springframework.beans.PropertyEditorRegistrySupport#registerCustomEditor(java.lang.Class<?>, java.beans.PropertyEditor)

PropertyEditorRegistrySupport方法还有一个createDefaultEditors方法,这个方法默认帮我们注入了

this.defaultEditors.put(short.class, new CustomNumberEditor(Short.class, false));
this.defaultEditors.put(Short.class, new CustomNumberEditor(Short.class, true));
this.defaultEditors.put(int.class, new CustomNumberEditor(Integer.class, false));
this.defaultEditors.put(Integer.class, new CustomNumberEditor(Integer.class, true));

等等,很多常用的类型都已以被注入了。

Formatter


Formatter也是一个接口,它继承两个接口,总共就两个方法

// 将字符串转换成目标对象
T parse(String text, Locale locale) throws ParseException
// 将目标对象转换成字符串
String print(T object, Locale locale);

自己定义一个Formatter:

public class MyDateFormatter implements Formatter<Date> {

    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.parse(text);
    }

    @Override
    public String print(Date object, Locale locale) {
        return null;
    }
}

如何使用这个Formatter,需要将这个Formatter注入到org.springframework.format.support.FormattingConversionServiceFactoryBean这个类的formatters中,因些需要在Spring的Bean配置xml中注入。

<bean id="myDateFormatterConverters" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="formatters">
            <set>
                <bean class="com.zmx.springmvc2.databind.MyDateFormatter"/>
            </set>
        </property>
</bean>

另外还需要:

<mvc:annotation-driven
            conversion-service="myDateFormatterConverters"/>

Converter


Converter也是一个接口,只有一个方法

// Convert the source of type S to target type T.
T convert(S source);

它和Formatter的parse不同的地方就是参数不是String类型。
自定义一个Converter

public class MyDateConverter implements Converter<String, Date> {
    
    @Override
    public Date convert(String source) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return simpleDateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

用法与Formatter一样,要注入到org.springframework.format.support.FormattingConversionServiceFactoryBean这个类的converters中

<bean id="myDateFormatterConverters" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.zmx.springmvc2.databind.MyDateConverter"/>
            </set>
        </property>
    </bean>
<mvc:annotation-driven
            conversion-service="myDateFormatterConverters"/>

总结一下:
1、PropertyEditor只能生效于某个Controller的数据从String到形参类型的转换,系统默认提供了常用类的转换。
2、Formatter需要在<mvc:annotation-driven conversion-service>和Spring的Bean中配置,可以做用于全局,只能将String转换成目标对象。
3、Converter需要在<mvc:annotation-driven conversion-service>和Spring的Bean中配置,可以做用于全局。可能接收Object类型转换成目标对象。

关于Formatter与Converter的其它用法后续再补充

上一篇 下一篇

猜你喜欢

热点阅读