SpringMVC框架:格式化与转换器

Converter(格式化)、Formatter(转换器)

一、Converter类

2、Converter:任何层都可以、Formatter:专门为Web层设计


3.Spring的Converter是将一种类型转换成为另一种类型的一个对象。创建Converter类为一下步骤:

1.org.springframework.core.convert.converter.Converter

这个接口的声明:

4.public interface Converter<S,T> -> S为源类型,T为目标类型

例:Long -> Double类型

public classname implements Converter<Long,Date>{}

实现方法:

T convert(S source) 方法是传入一个S 的源类型

%重点%

1、利用bean 的构造器方法进行可以配置注入

编写bean -> org.springframework.context.support.conversion.ServicefactoryBean;

<properties name = "converters">

<list><bean class = "自定义类名全路径"/></list>

</properties>

2、定义配置一个

<mvc:anntation-driven conversion-service = “对应的beanid”>

3.其他注意事项:

BindResulting与getFieldError()方法的使用

二、Formatter类

1、限制Source-String,必须为:源类型:只可以为String,适用于Web层次结构

2、例子:转换为类型:

public interface Formatter<T>

org.springfamework.format.Formatter

3、方法:parse()、print()

4.在Spring 的配置文件中配置一个FactoryBean 具体为什么不多说了,剩下的和Converter类差不多此外要说明的是Formatter-formatterRegister 实现 registerFormatters 方法 - addFormatter(类)