在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
需要複寫兩個方法,分別是parse
和parse
將字符串轉換爲對象,
寫一個控制器來測試轉換器:
@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
接口進行類型轉換,舉個簡單的String
轉Integer
的例子,實現方式和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);
}
};
}
}