Spring MVC 转换器与格式化

自定义转换器和格式化

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值