- spirng mvc中要实现自定义的转换有2种途径:
- 定义一个配置类实现Converter接口
- 定义一个配置类实现Formatter接口
- 然后在配置类中配置自定义的转化规则
- 最后要把我们的配置类注册到mvc的配置里面去,有2种方式,这里只讲java方式配置
定义Converter配置类
```java import org.springframework.core.convert.converter.Converter;
public class MyDateConverter implements Converter
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyy-MM-dd HH:mm:ss”); Date date = null; try { date = simpleDateFormat.parse(str); } catch (ParseException e) { e.printStackTrace(); }
return date; } }
<a name="F9dVk"></a># 定义Formatter配置类```javapublic MyDateFormatter implements Formatter{public DateFormatter(String datePattern) {dateFormat = new SimpleDateFormat("MM-dd-yyyy");}@Overridepublic String print(Date object, Locale locale) {return dateFormat.format(object);}@Overridepublic Date parse(String text, Locale locale) throws ParseException {return dateFormat.parse(text);}}@Override //这里是将配置类注册到mvc里面去public void addFormatters(FormatterRegistry registry) {registry.addConverter(new MyDateConverter());// registry.addFormatter(new MyDateFormatter());}
