自定义转换器和格式化
Spring MVC 内置的将一种对象类型转换为另一种对象类型的接口实现。
Converter(转换器):通用元件,源类型可以是任意的对象类型。
// 实现 Converter 接口,S(source)表示源类型,T(target)表示目标类型。
public interface Converter<S, T> {
@Nullable
T convert(S source);
}
实现代码[ Java ]:将指定格式的字符串转换为LocalDate类型。
import org.springframework.core.convert.converter.Converter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateConverter implements Converter<String, LocalDate> {
// 字符串的日期格式
private String pattern;
public DateConverter(String pattern) {
this.pattern = pattern;
}
@Override
public LocalDate convert(String source) {
LocalDate localDate = null;
try{
localDate = LocalDate.parse(source, DateTimeFormatter.ofPattern(this.pattern));
}catch (Exception e){
e.printStackTrace();
}
return localDate;
}
}
Fomatter(格式化):专为Web层而设计,源类型必须是一个String类型。
// 实现 Fomatter 接口,T(target) 表示目标类型。
public interface Formatter<T> extends Printer<T>, Parser<T> {}
实现代码[ Java ]:将指定格式的字符串转换为LocalDate类型。
import org.springframework.format.Formatter;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class DateFormatter implements Formatter<LocalDate> {
private DateTimeFormatter formatter;
private String pattern;
public DateFormatter(String pattern) {
this.pattern = pattern;
formatter = DateTimeFormatter.ofPattern(pattern);
}
@Override // 将对象解析成目标类型
public LocalDate parse(String s, Locale locale) throws ParseException {
try {
return LocalDate.parse(s,DateTimeFormatter.ofPattern(pattern));
}catch (Exception e){
throw new IllegalArgumentException("Please use this pattern\"" + pattern +"\"");
}
}
@Override // 返回目标对象的字符串表示法
public String print(LocalDate date, Locale locale) {
return date.format(formatter);
}
}
推荐使用 Converter,它的接口实现更为简单!
演示案例:示例代码
提取码:cjpd