• spirng mvc中要实现自定义的转换有2种途径:
    • 定义一个配置类实现Converter接口
    • 定义一个配置类实现Formatter接口
  • 然后在配置类中配置自定义的转化规则
  • 最后要把我们的配置类注册到mvc的配置里面去,有2种方式,这里只讲java方式配置

    定义Converter配置类

    ```java import org.springframework.core.convert.converter.Converter;

public class MyDateConverter implements Converter { @Override //这里是将配置类注册到mvc里面去 public void addFormatters(FormatterRegistry registry) { registry.addConverter(new MyDateConverter()); // registry.addFormatter(new MyDateFormatter()); } @Override //这里将String进行我们自定义的转换然后返回 public Date convert(String str) {

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

  1. <a name="F9dVk"></a>
  2. # 定义Formatter配置类
  3. ```java
  4. public MyDateFormatter implements Formatter{
  5. public DateFormatter(String datePattern) {
  6. dateFormat = new SimpleDateFormat("MM-dd-yyyy");
  7. }
  8. @Override
  9. public String print(Date object, Locale locale) {
  10. return dateFormat.format(object);
  11. }
  12. @Override
  13. public Date parse(String text, Locale locale) throws ParseException {
  14. return dateFormat.parse(text);
  15. }
  16. }
  17. @Override //这里是将配置类注册到mvc里面去
  18. public void addFormatters(FormatterRegistry registry) {
  19. registry.addConverter(new MyDateConverter());
  20. // registry.addFormatter(new MyDateFormatter());
  21. }