spring中的類型轉換方式,Formatter和Converter

本文原文鏈接

在web應用中實現類型轉換的兩種方式

一:實現org.springframework.format.datetime.DateFormatter接口,對於一個常見的字符串轉日期的Formatter可有如下實現:

@Configuration
public class CommonConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(dateFormatter());
    }
	
    private Formatter<Date> dateFormatter(){
      return new Formatter<Date>() {
          private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
          @Override
          public Date parse(String text, Locale locale) throws ParseException {
              if(text.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}")){
                return simpleDateFormat.parse(text);
              }
              String errMsg = "錯誤的日期格式{"+text+"},要求格式{yyyy-MM-dd HH:mm}";
              throw new IllegalArgumentException(errMsg);
          }

          @Override
          public String print(Date date, Locale locale) {

              return simpleDateFormat.format(date);
          }
      };
    };
}

在上面例子中,需要注意的是:

  • 配置類需要實現WebMvcConfigure接口,並複寫addFormatters方法,將自己的Formatter註冊進去
  • 實現Formatter需要複寫兩個方法,分別是parseprintparse將字符串轉換爲對象,print將對象轉換爲字符串

寫一個控制器來測試轉換器:

@Controller
@RequestMapping("/test")
public class TestController{
	@GetMapping("/str2Date")
	@ResponseBody
	public Date str2Date(Date date){
		return date;
	}
}

訪問http://localhost/test/str2Date?date=2019-12-13%2023:22,瀏覽器輸出2019-12-13 23:22
訪問http://localhost/test/str2Date?date=2019-12-13,後臺報錯錯誤的日期格式{2019-12-13},要求格式{yyyy-MM-dd HH:mm}
可以看出,瀏覽器中輸入的參數date爲字符串格式,後臺接收時是用的Date,我們自定義的Formatter對這兩種類型進行了轉換

二:實現Converter接口進行類型轉換,舉個簡單的StringInteger的例子,實現方式和Formatter差不多,不再詳細說明

@Configuration
public class CommonConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(stringIntegerConverter());
    }
    private Converter<String,Integer> stringIntegerConverter(){
        return new Converter<String, Integer>() {
            @Override
            public Integer convert(String source) {

                return Integer.valueOf(source);
            }
        };
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章